官網(wǎng): http://square.github.io/okhttp/
github地址:https://github.com/square/okhttp
簡介
HTTP是現(xiàn)代應用網(wǎng)絡的方式呼盆。這是我們如何交換數(shù)據(jù)和媒體。有效地進行HTTP使您的東西加載更快腿时,并節(jié)省帶寬批糟。
OkHttp是默認情況下高效的HTTP客戶端:
HTTP / 2支持允許對同一主機的所有請求共享套接字徽鼎。
連接池減少請求延遲(如果HTTP / 2不可用)悄但。
透明GZIP縮小下載大小。
響應緩存可以完全避免重復請求的網(wǎng)絡净嘀。
當網(wǎng)絡很麻煩時侠讯,OkHttp堅持不懈:它將從常見的連接問題中靜默地恢復。如果您的服務有多個IP地址溜嗜,如果第一個連接失敗炸宵,OkHttp將嘗試替代地址土全。這對于IPv4 + IPv6以及在冗余數(shù)據(jù)中心中托管的服務是必需的。 OkHttp啟動與現(xiàn)代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);
}
});
}
}
然后運行和我們看到返回的數(shù)據(jù):
{"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"]}]}