HTTP客户端--OkHttp
原文网址:HTTP客户端—OkHttp_IT利刃出鞘的博客-CSDN博客
其他网址
OkHttp使用完全教程_along-CSDN博客
简介
其他网址
基本使用——OkHttp3详细使用教程_薛瑄的博客-CSDN博客_okhttp3使用
OkHttp官网地址:OkHttp
OkHttp GitHub地址:https://github.com/square/okhttp
依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.7.2</version>
</dependency>
概述
OkHttp为高效而生,其对高效问题的解决方案是
- 提供了对 HTTP/2 和 SPDY 的支持,这使得对同一个主机发出的所有请求都可以共享相同的套接字连接
- 如果 HTTP/2 和 SPDY 不可用,OkHttp 会使用连接池来复用连接以提高效率
- 提供了对 GZIP 的默认支持来降低传输内容的大小
- 提供了对 HTTP 响应的缓存机制,可以避免不必要的网络请求
- 当网络出现问题时,OkHttp 会自动重试一个主机的多个 IP 地址
实例
private OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
private String http(Request request) throws IOException {
Response response = okHttpClient.newCall(request).execute();
ResponseBody rb = response.body();
if (rb == null) {
throw new RuntimeException("返回值为null");
}
return rb.string();
}
Map<String, String> params = new HashMap<>();
params.put("title", "this is title");
params.put("name", "Tony");
String reqJson = JSON.toJSONString(params);
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), reqJson);
Request httpReq = new Request.Builder()
.url("http://xxx.com/xxx")
.header("header1_key", "header1_value")
.post(body)
.build();
String resp = http(httpReq);
OkHttp3设计思路
通过Diapatcher不断从RequestQueue中取出请求(Call),根据是否已缓存从内存缓存或是服务器取得请求的数据
还没有评论,来说两句吧...