官网: http://square.github.io/okhttp/
github地址:https://github.com/square/okhttp
简介
HTTP是现代应用网络的方式。这是我们如何交换数据和媒体。有效地进行HTTP使您的东西加载更快,并节省带宽。
OkHttp是默认情况下高效的HTTP客户端:
HTTP / 2支持允许对同一主机的所有请求共享套接字。
连接池减少请求延迟(如果HTTP / 2不可用)。
透明GZIP缩小下载大小。
响应缓存可以完全避免重复请求的网络。
当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中静默地恢复。如果您的服务有多个IP地址,如果第一个连接失败,OkHttp将尝试替代地址。这对于IPv4 + IPv6以及在冗余数据中心中托管的服务是必需的。 OkHttp启动与现代TLS功能(SNI,ALPN)的新连接,如果握手失败,则返回TLS 1.0。
使用OkHttp很容易它的请求/响应API设计有流畅的构建器和不变性。它支持同步阻塞调用和具有回调的异步调用。
OkHttp支持Android 2.3及以上版本。对于Java,最低要求是1.7。
OkHttp的初始化
OkHttp的初始化是比较简单的,整体思路是:
- 初始化OkHttp客户端
- 初始化一个Request
- 由客户端和Request生成一个Call
- call调用enqueue或者execute
Talk is cheap show me the code
public class TestMain {
private static final long cacheSize = 1024*1024*20;//缓存文件最大限制大小20M
private static String cachedirectory = "" + "/caches"; //设置缓存文件路径
private static Cache cache = new Cache(new File(cachedirectory), cacheSize); //
public static void main(String[] args) {
//初始化OkHttp客户端
OkHttpClient okHttpClient=new OkHttpClient.Builder().cache(cache).build();
RequestBody formBody = new FormBody.Builder()
.add("pageNum", "10")
.add("page","1")
.add("token","df670781b9261c934c8c157f3905fb76")
.build();
//初始化一个Request
final Request request=new Request.Builder().url("http://www.tuinar.cn/api/rcsubcompany.html").post(formBody).build();
//由客户端和Request生成一个Call
Call call = okHttpClient.newCall(request);
//call调用enqueue或者execute
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String jsonStr=response.body().string();
System.out.println(jsonStr);
}
});
}
}
然后运行和我们看到返回的数据:
{"status":1,"msg":"\u83b7\u53d6\u6210\u529f","data":[{"id":"23","uid":"55","name":"\u676d\u5dde\u5bb9\u65b9\u4fe1\u606f\u6280\u672f\u6709\u9650\u516c\u53f8","logoimg":"\/static\/attachment\/company\/201603\/c9735719bb71c8491e342ab2c9d74330.jpg","fzjd":"\u521d\u521b\u578b","qygm":"20-99\u4eba","cates":"\u8ba1\u7b97\u673a\u8f6f\u4ef6\/\u786c\u4ef6","hotjobs":["\u9879\u76ee\u7ecf\u7406","\u8f6f\u4ef6\u6d4b\u8bd5\u5de5\u7a0b\u5e08","\u9ad8\u7ea7\u6587\u6863\u4e13\u5458"]},{"id":"39","uid":"97","name":"\u6df1\u5733\u5e02\u9177\u7ef4\u667a\u8054\u79d1\u6280\u6709\u9650\u516c\u53f8","logoimg":"\/static\/attachment\/company\/201604\/b134fc7e766b3d2af0cc3247032c22a5.jpg","fzjd":null,"qygm":null,"cates":"\u7535\u5b50\/\u534a\u5bfc\u4f53\/\u96c6\u6210\u7535\u8def","hotjobs":["ID\u5de5\u7a0b\u5e08"]},{"id":"46","uid":"149","name":"\u676d\u5dde\u5de5\u732b\u79d1\u6280\u6709\u9650\u516c\u53f8","logoimg":"\/static\/attachment\/company\/201703\/8e249c47daf38738f8e56ad1bed162a6.jpg","fzjd":null,"qygm":"20-99\u4eba","cates":"\u4e92\u8054\u7f51\/\u7535\u5b50\u5546\u52a1","hotjobs":["\u533a\u57df\u7ecf\u7406\/\u5927\u533a\u7ecf\u7406\uff08\u6709\u7ecf\u9a8c\u3001\u80fd\u51fa\u5dee\uff09","\u65b0\u5a92\u4f53\u8fd0\u8425\u4e13\u5458"]}]}
网友评论