学习记录,不喜勿喷
什么是OkHttp
一般在Java平台上,我们会使用Apache HttpClient作为Http客户端,用于发送 HTTP 请求,并对响应进行处理。比如可以使用http客户端与第三方服务(如SSO服务)进行集成,当然还可以爬取网上的数据等。OKHttp与HttpClient类似,也是一个Http客户端,提供了对 HTTP/2 和 SPDY 的支持,并提供了连接池,GZIP 压缩和 HTTP 响应缓存功能。
OkHttp优点
(1)支持HTTP2/SPDY(SPDY是Google开发的基于TCP的传输层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验)
(2)socket自动选择最好路线,并支持自动重连,拥有自动维护的socket连接池,减少握手次数,减少了请求延迟,共享Socket,减少对服务器的请求次数
(3)基于Headers的缓存策略减少重复的网络请求
(4)拥有Interceptors轻松处理请求与响应(自动处理GZip压缩)
OkHttp功能
(1)一般的get请求
(2)一般的post请求
(3)基于Http的文件上传
(4)文件下载
(5)上传下载的进度回调
(6)加载图片
(7)支持请求回调,直接返回对象、对象集合
(8)支持session的保持
(9)支持自签名网站https的访问,提供方法设置下证书就行
(10)支持取消某个请求
数据测试接口
package com.waves.controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/dataApi")
public class ResponseDataController {
@GetMapping("/getData")
public Map<String,Object> getData(@RequestParam("pageIndex")String pageIndex){
Map<String,Object> map = new HashMap<>();
map.put("username","小明");
map.put("password","123456");
map.put("age","18");
map.put("endSchool","中国大学");
List<Map<String,Object>> list = new ArrayList<>();
list.add(map);
Map<String,Object> map2 = new HashMap<>();
map2.put("total",list.size());
map2.put("code",200);
map2.put("data",list);
return map2;
}
@PostMapping("/postData")
public Map<String,Object> postData(@RequestBody Map<String,Object> params){
Map<String,Object> map = new HashMap<>();
map.put("username","小红");
map.put("password","123456");
map.put("age","18");
map.put("school","中国大学");
List<Map<String,Object>> list = new ArrayList<>();
list.add(map);
Map<String,Object> map2 = new HashMap<>();
map2.put("total",list.size());
map2.put("code",200);
map2.put("data",list);
return map2;
}
}
OkHttp POST请求接口
package com.waves.controller;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/okHttpApi")
public class OkHttpController {
@PostMapping("/okHttpPost")
public Map<String,Object> okHttpPost(@RequestBody Map<String,Object> params){
try {
//json字符串的两种形式
String k = "{\n" +
"\t\"pageIndex\": \"1\",\n" +
"\t\"pageSize\": \"10\",\n" +
"\t\"userName\": \"xiaoming\"\n" +
"}";
JSONObject json2 = new JSONObject();
json2.put("pageIndex","1");
json2.put("pageSize","20");
json2.put("userName","xiaoming");
//创建一个OkHttpClient
OkHttpClient client = new OkHttpClient();
//设置请求头
MediaType mediaType = MediaType.parse("application/json");
//请求体
okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(mediaType,k);
//创建一个request
Request request = new Request.Builder()
.post(requestBody)
.url("http://localhost:8080/dataApi/postData")
.addHeader("content-type","application/json")
.build();
//获得返回
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//获取返回值
String responseData = response.body().string();
//将json字符串转为JSONObject
JSONObject data = JSONObject.parseObject(responseData);
//将jsonObject 转为Map
Map<String,Object> map2 = data.toJavaObject(Map.class);
return map2;
}catch (Exception e){
return new HashMap<>();
}
}
}
OkHttp GET方式请求接口
@GetMapping("/okHttpGet")
public Map<String,Object> okHttpGet(@RequestBody Map<String,Object> params){
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url("http://localhost:8080/dataApi/getData?pageIndex=1")
// .addHeader("content-type","application/json")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//获取返回值
String responseData = response.body().string();
//将json字符串转为JSONObject
JSONObject data = JSONObject.parseObject(responseData);
//将jsonObject 转为Map
Map<String,Object> map2 = data.toJavaObject(Map.class);
return map2;
}catch (Exception e){
return new HashMap<>();
}
}
项目pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.wavesgroupId>
<artifactId>waves_okhttpartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>waves_okhttpname>
<description>Okhtp project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASEspring-boot.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.72version>
dependency>
<dependency>
<groupId>com.squareup.okhttp3groupId>
<artifactId>okhttpartifactId>
<version>4.9.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<scope>testscope>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>${spring-boot.version}version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.1version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<version>2.3.7.RELEASEversion>
<configuration>
<mainClass>com.waves.WavesOkhttpApplicationmainClass>
configuration>
<executions>
<execution>
<id>repackageid>
<goals>
<goal>repackagegoal>
goals>
execution>
executions>
plugin>
plugins>
build>
project>