前言
HTTP是一種比較流行的用于數(shù)據(jù)和多媒體流數(shù)據(jù)的交換的網(wǎng)絡(luò)協(xié)議簿寂。高效的使用HTTP可以使你的應(yīng)用加載更快并節(jié)省帶寬。
OKhttp就是一個(gè)可以高效使用HTTP的客戶(hù)端, Okhttp包含一下四大特性:
- 支持 HTTP/2 允許對(duì)同一主機(jī)的所有請(qǐng)求共享Socket
- 使用連接池猾昆,減少了請(qǐng)求的延遲
- 支持GZIP 減小了傳輸?shù)拇笮?/li>
- 支持響應(yīng)緩沖,完全避免了重復(fù)請(qǐng)求的情況出現(xiàn)
更多介紹內(nèi)容參見(jiàn)官網(wǎng):
https://square.github.io/okhttp/
其他相關(guān)文章
OkHttp 4.0 Kotlin源碼分析 (一) 同步和異步請(qǐng)求基本用法
OkHttp 4.0 Kotlin源碼分析 (二) 基本的數(shù)據(jù)對(duì)象以及Call類(lèi)分析
OkHttp 4.0 Kotlin源碼分析 (三) Dispatcher分發(fā)器流程控制
1. OKhttp3 的基本用法
1.1 版本說(shuō)明
Okhttp 3.12.x supports Android 2.3+ (API level 9+) and Java 7+ , 在2020.12.31之前將對(duì)3.12.x版本提供關(guān)鍵性修復(fù)胶背。
OkHttp 3.13.x supports Android 5.0+ (API level 21+) and Java 8+.
1.2 庫(kù)的下載
在gradle文件中加入一下代碼:
implementation("com.squareup.okhttp3:okhttp:3.13.1")
1.3 Okhttp的使用范例
范例 (一)
這是同步Get請(qǐng)求巷嚣,程序完成的任務(wù)是獲取一個(gè)URL,并將獲取到的內(nèi)容轉(zhuǎn)換為String進(jìn)行打印钳吟。
package okhttp3.guide;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetExample {
//1. 創(chuàng)建OkhttpClient 對(duì)象
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
//2. 創(chuàng)建請(qǐng)求的Request 對(duì)象
Request request = new Request.Builder()
.url(url)
.build();
//3. 在Okhttp中創(chuàng)建Call 對(duì)象廷粒,將request和Client進(jìn)行綁定
//4. 執(zhí)行Call對(duì)象(call 是interface 實(shí)際執(zhí)行的是RealCall)中的`execute`方法
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
范例 (二)
這是一個(gè)android 程序,完成了一次異步的POST請(qǐng)求红且,將數(shù)據(jù)Post到服務(wù)器.
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final String TAG = "OkHttp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json = bowlingJson("Jesse", "Jake");
String url = "http://www.roundsapp.com/post";
//1. 創(chuàng)建OkhttpClient 對(duì)象
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
//2. 創(chuàng)建請(qǐng)求的Request 對(duì)象
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//3. 在Okhttp中創(chuàng)建Call 對(duì)象坝茎,將request和Client進(jìn)行綁定
Call call = client.newCall(request);
//4. 執(zhí)行Call對(duì)象(call 是interface 實(shí)際執(zhí)行的是RealCall)中的 `enqueue`方法
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, response.body().toString());
}
});
}
String bowlingJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1367702411696,"
+ "'dateStarted':1367702378785,"
+ "'players':["
+ "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
+ "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
+ "]}";
}
}
1.4 總結(jié)
以上是Okhttp的基本使用方法,列舉了兩個(gè)范例分別是暇番,
- GET請(qǐng)求的同步調(diào)用
- POST請(qǐng)求的異步調(diào)用
對(duì)比范例中的代碼注釋?zhuān)还苁峭竭€是異步請(qǐng)求都有四個(gè)關(guān)鍵的步驟:
- 創(chuàng)建OkhttpClient 對(duì)象
- 創(chuàng)建請(qǐng)求的Request 對(duì)象
- 在Okhttp中創(chuàng)建Call 對(duì)象嗤放,將request和Client進(jìn)行綁定
- 執(zhí)行Call對(duì)象(call 是interface 實(shí)際執(zhí)行的是RealCall)中的
execute()
或enqueue()
方法
- 執(zhí)行Call對(duì)象(call 是interface 實(shí)際執(zhí)行的是RealCall)中的
我們發(fā)現(xiàn),同步和異步請(qǐng)求唯一區(qū)別是壁酬,最后調(diào)用的Call對(duì)象的方法不同次酌, 同步調(diào)用是execute()
方法,而異步調(diào)用的是enqueue()
舆乔。
疑問(wèn)岳服?
1.OkhttpClient和Request對(duì)象是什么作用,又是怎么進(jìn)行綁定的呢希俩?
2.Call對(duì)象的這兩方法有什么不同呢吊宋,又是怎么進(jìn)行同、異步處理的颜武?