1、简介
OkHttp 是一个默认高效的 HTTP 客户端:
- HTTP/2 支持允许对同一主机的所有请求共享一个套接字。
- 连接池减少了请求延迟(如果 HTTP/2 不可用)。
- 透明 GZIP 缩小了下载大小。
- 响应缓存完全避免了网络重复请求。
2、引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
3、获取 OkHttpClient 对象
在使用 OkHttp
发送 HTTP 请求时,首先需要获取一个 OkHttpClient
对象,获取 OkHttpClient
对象的方式很简单,在 OkHttp 中大量使用了 Builder 模式。获取 OkHttpClient
对象的方法如下所示:
-
获取默认配置对象
OkHttpClient httpClient = new OkHttpClient.Builder().build();
-
获取自定配置对象
在获取对象时可以指定,连接超时、读写超时、拦截器等配置,如下所示:
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(30))
.readTimeout(Duration.ofSeconds(60))
.writeTimeout(Duration.ofSeconds(60))
.callTimeout(Duration.ofSeconds(120))
.addInterceptor(chain -> {
Request request = chain.request();
return chain.proceed(request);
})
.eventListener(new EventListener() {
@Override
public void callEnd(@NotNull Call call) {
LOGGER.info("----------callEnd--------");
super.callEnd(call);
}
})
.build();
4、GET 请求
GET
请求的执行步骤如下:
-
构造 Request 对象
Request request = new Request.Builder()
.get()
.url("http://localhost:10010/user/map?name=zhangsan&a=a&age=20")
.addHeader("Content-Type", "text/plain")
.build();
-
将 Request 封装为 Call
Call call = httpClient.newCall(request);
-
执行请求 (同步或异步)
同步请求
Response response = call.execute();
异步请求
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
LOGGER.error("请求 {} 出现异常 {}", call.request().url(), e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String body = response.body().toString();
LOGGER.info("请求 {} 的响应结果为 {}", call.request().url(), body);
}
});
5、POST 请求
POST
请求的构建步骤与GET
相似,区别是,在构建 Request
对象时 在post()
方法中,设置需要发送的数据,发送的数据可为目前流行的 JSON
格式数据,也可以模拟 Form
表单提交的数据,操作如下所示:
-
构建Form表单数据
FormBody formBody = new FormBody.Builder()
.addEncoded("name", "张三")
.add("age", "20")
.add("a", "ag")
.build();
-
构造 JSON 数据
JSONObject json = new JSONObject();
json.put("name", "张三");
json.put("age", 20);
MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
RequestBody requestBody = RequestBody.create(json.toJSONString(), mediaType);
-
构造Request对象
Request request = new Request.Builder()
.post(formBody)
.url("http://localhost:10010/user/obj")
.build();
构建完Request
对象后的步骤,就与GET
请求相似,构建 Call
对象然后,在发送同步
或异步
请求
6、上传
在OkHttp
中 进行文件的上传,是相当简单的,在发送 POST
请求时,只需要构造一个MultipartBody
对象即可,MultipartBody
对象可以发送 文件数据,也可以发送基本类型的数据。
File file = new File("F:/20150703212056_Yxi4L.png");
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("name", "admin")
.addFormDataPart("password", "admin")
.addFormDataPart("file", "20150703212056_Yxi4L.png",
RequestBody.create( file, MediaType.parse("image/png")))
.build();
Request request = new Request.Builder()
.post(multipartBody)
.url("http://localhost:10010/user/upload")
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
7、总结
OkHttp
作为网络请求工具,简单且功能强大,并且其大量使用了 构建者模式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)