http://blog.csdn.net/lmj623565791/article/details/47911083
Okhttp 簡(jiǎn)介
支持連接同一地址的鏈接共享同一個(gè) Socket ,通過(guò)連接池來(lái)減小響應(yīng)延遲, 還有透明的GZIP壓縮, 請(qǐng)求緩存等優(yōu)勢(shì),其核心主要由路由、連接協(xié)議、攔截器、代理、安全性認(rèn)證、連接池及網(wǎng)絡(luò)適配,攔截器主要是指添加、移除或者轉(zhuǎn)換請(qǐng)求或者回應(yīng) 頭部信息。
主要功能:
1、聯(lián)網(wǎng)請(qǐng)求文本數(shù)據(jù)
2、大文件下載
3、大文件上傳
4、請(qǐng)求圖片
有兩種關(guān)聯(lián)方式
1、直接導(dǎo)入 jar 包,然后將 jar 包添加到項(xiàng)目中
2、在 Gradle 中添加: compile 'com.squareup.okhttp3:okhttp:3.4.1'
使用原生的 okhttp 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
//使用原生的 okhttp 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù), get 和 post
OkHttpClient client = new OkhttpClient();
//get 請(qǐng)求,只能在子線程中調(diào)用
private String get(String url) throws IOException{
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
//post 請(qǐng)求,可以拿到數(shù)據(jù)也可以上傳,這兒我們是拿數(shù)據(jù)
public static final MediaType JSON=MediaType.parse("application/json;charset=utf-8");//配置編碼
private String post(String url,String json) throws IOException{
RequestBody body=Request.create(JSON,json);
Request request=new Request.Builder()
.url(url)
.post(body)
.build();
Response response = Client.newCall(request).execute();
return response.body().string();
}