I.簡介
HTTP是現(xiàn)代應(yīng)用常用的一種交換數(shù)據(jù)和媒體的網(wǎng)絡(luò)方式稽坤,高效地使用HTTP能讓資源加載更快,節(jié)省帶寬渔伯。OkHttp是一個高效的HTTP客戶端顶霞,它有以下默認特性:
- 支持HTTP/2,允許所有同一個主機地址的請求共享同一個socket連接
- 連接池減少請求延時
- 透明的GZIP壓縮減少響應(yīng)數(shù)據(jù)的大小
- 緩存響應(yīng)內(nèi)容锣吼,避免一些完全重復(fù)的請求
當(dāng)網(wǎng)絡(luò)出現(xiàn)問題的時候OkHttp依然堅守自己的職責(zé)确丢,它會自動恢復(fù)一般的連接問題,如果你的服務(wù)有多個IP地址吐限,當(dāng)?shù)谝粋€IP請求失敗時,OkHttp會交替嘗試你配置的其他IP褂始,OkHttp使用現(xiàn)代TLS技術(shù)(SNI, ALPN)初始化新的連接诸典,當(dāng)握手失敗時會回退到TLS 1.0。
note: OkHttp 支持 Android 2.3 及以上版本Android平臺崎苗, 對于 Java, JDK 1.7及以上.
對于Okhttp3的源碼閱讀預(yù)計會寫3篇文章來總結(jié):
II.使用
OkHttp的使用是非常簡單的. 它的請求/響應(yīng) API 使用構(gòu)造器模式builders來設(shè)計,它支持阻塞式的同步請求和帶回調(diào)的異步請求胆数。
Download OkHttp3
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
當(dāng)你看到這的時候肌蜻,可能最新的穩(wěn)定版已經(jīng)不是3.10.0
了,你需要移步官方GitHub來查看最新版本必尼。 官方地址 https://github.com/square/okhttp蒋搜,另外不要忘了在清單文件聲明訪問Internet的權(quán)限篡撵,如果使用 DiskLruCache
,那還得聲明寫外存的權(quán)限豆挽。
1.1. 異步GET請求
-new OkHttpClient;
-構(gòu)造Request對象育谬;
-通過前兩步中的對象構(gòu)建Call對象;
-通過Call#enqueue(Callback)方法來提交異步請求帮哈;
String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默認就是GET請求膛檀,可以不寫
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
異步發(fā)起的請求會被加入到 Dispatcher
中的 runningAsyncCalls
雙端隊列中通過線程池來執(zhí)行。
1.2. 同步GET請求
前面幾個步驟和異步方式一樣娘侍,只是最后一部是通過 Call#execute()
來提交請求咖刃,注意這種方式會阻塞調(diào)用線程,所以在Android中應(yīng)放在子線程中執(zhí)行憾筏,否則有可能引起ANR異常嚎杨,Android3.0
以后已經(jīng)不允許在主線程訪問網(wǎng)絡(luò)。
String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.d(TAG, "run: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
2.1. POST方式提交String
這種方式與前面的區(qū)別就是在構(gòu)造Request對象時踩叭,需要多構(gòu)造一個RequestBody對象磕潮,用它來攜帶我們要提交的數(shù)據(jù)。在構(gòu)造 RequestBody
需要指定MediaType
容贝,用于描述請求/響應(yīng) body
的內(nèi)容類型自脯,關(guān)于 MediaType
的更多信息可以查看 RFC 2045,RequstBody的幾種構(gòu)造方式:
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
String requestBody = "I am Jdqm.";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(mediaType, requestBody))
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.d(TAG, headers.name(i) + ":" + headers.value(i));
}
Log.d(TAG, "onResponse: " + response.body().string());
}
});
響應(yīng)內(nèi)容
http/1.1 200 OK
Date:Sat, 10 Mar 2018 05:23:20 GMT
Content-Type:text/html;charset=utf-8
Content-Length:18
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:52
X-RateLimit-Reset:1520661052
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Content-Security-Policy:default-src 'none'
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Content-Type-Options:nosniff
X-Frame-Options:deny
X-XSS-Protection:1; mode=block
X-Runtime-rack:0.019668
Vary:Accept-Encoding
X-GitHub-Request-Id:1474:20A83:5CC0B6:7A7C1B:5AA36BC8
onResponse: <p>I am Jdqm.</p>
2.2 POST方式提交流
RequestBody requestBody = new RequestBody() {
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse("text/x-markdown; charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("I am Jdqm.");
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.d(TAG, headers.name(i) + ":" + headers.value(i));
}
Log.d(TAG, "onResponse: " + response.body().string());
}
});
2.3. POST提交文件
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
OkHttpClient okHttpClient = new OkHttpClient();
File file = new File("test.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(mediaType, file))
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.d(TAG, headers.name(i) + ":" + headers.value(i));
}
Log.d(TAG, "onResponse: " + response.body().string());
}
});
2.4. POST方式提交表單
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.d(TAG, headers.name(i) + ":" + headers.value(i));
}
Log.d(TAG, "onResponse: " + response.body().string());
}
});
提交表單時斤富,使用 RequestBody
的實現(xiàn)類FormBody
來描述請求體膏潮,它可以攜帶一些經(jīng)過編碼的 key-value
請求體,鍵值對存儲在下面兩個集合中:
private final List<String> encodedNames;
private final List<String> encodedValues;
2.5. POST方式提交分塊請求
MultipartBody 可以構(gòu)建復(fù)雜的請求體满力,與HTML文件上傳形式兼容焕参。多塊請求體中每塊請求都是一個請求體,可以定義自己的請求頭油额。這些請求頭可以用來描述這塊請求叠纷,例如它的 Content-Disposition
。如果 Content-Length
和 Content-Type
可用的話潦嘶,他們會被自動添加到請求頭中涩嚣。
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void postMultipartBody() {
OkHttpClient client = new OkHttpClient();
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
MultipartBody body = new MultipartBody.Builder("AaB03x")
.setType(MultipartBody.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});
}
III.攔截器-interceptor
OkHttp的攔截器鏈可謂是其整個框架的精髓,用戶可傳入的 interceptor
分為兩類:
①一類是全局的 interceptor
掂僵,該類 interceptor
在整個攔截器鏈中最早被調(diào)用航厚,通過 OkHttpClient.Builder#addInterceptor(Interceptor)
傳入;
②另外一類是非網(wǎng)頁請求的 interceptor
锰蓬,這類攔截器只會在非網(wǎng)頁請求中被調(diào)用幔睬,并且是在組裝完請求之后,真正發(fā)起網(wǎng)絡(luò)請求前被調(diào)用芹扭,所有的 interceptor
被保存在 List<Interceptor> interceptors
集合中麻顶,按照添加順序來逐個調(diào)用赦抖,具體可參考 RealCall#getResponseWithInterceptorChain()
方法。通過 OkHttpClient.Builder#addNetworkInterceptor(Interceptor)
傳入澈蚌;
這里舉一個簡單的例子摹芙,例如有這樣一個需求,我要監(jiān)控App通過 OkHttp
發(fā)出的所有原始請求宛瞄,以及整個請求所耗費的時間浮禾,針對這樣的需求就可以使用第一類全局的 interceptor
在攔截器鏈頭去做。
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder()
.url("http://www.publicobject.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, "onResponse: " + response.body().string());
body.close();
}
}
});
public class LoggingInterceptor implements Interceptor {
private static final String TAG = "LoggingInterceptor";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.nanoTime();
Log.d(TAG, String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long endTime = System.nanoTime();
Log.d(TAG, String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (endTime - startTime) / 1e6d, response.headers()));
return response;
}
}
針對這個請求份汗,打印出來的結(jié)果
Sending request http://www.publicobject.com/helloworld.txt on null
User-Agent: OkHttp Example
Received response for https://publicobject.com/helloworld.txt in 1265.9ms
Server: nginx/1.10.0 (Ubuntu)
Date: Wed, 28 Mar 2018 08:19:48 GMT
Content-Type: text/plain
Content-Length: 1759
Last-Modified: Tue, 27 May 2014 02:35:47 GMT
Connection: keep-alive
ETag: "5383fa03-6df"
Accept-Ranges: bytes
注意到一點是這個請求做了重定向盈电,原始的 request url
是 http://www.publicobject.com/helloworld.tx
,而響應(yīng)的 request url
是 https://publicobject.com/helloworld.txt
杯活,這說明一定發(fā)生了重定向匆帚,但是做了幾次重定向其實我們這里是不知道的,要知道這些的話旁钧,可以使用 addNetworkInterceptor()
去做吸重。更多的關(guān)于 interceptor
的使用以及它們各自的優(yōu)缺點,請移步OkHttp官方說明文檔歪今。
IV. 自定義dns服務(wù)
Okhttp默認情況下使用的是系統(tǒng)
V.其他
- 推薦讓
OkHttpClient
保持單例嚎幸,用同一個OkHttpClient
實例來執(zhí)行你的所有請求,因為每一個OkHttpClient
實例都擁有自己的連接池和線程池寄猩,重用這些資源可以減少延時和節(jié)省資源嫉晶,如果為每個請求創(chuàng)建一個OkHttpClient
實例,顯然就是一種資源的浪費田篇。當(dāng)然替废,也可以使用如下的方式來創(chuàng)建一個新的OkHttpClient
實例,它們共享連接池泊柬、線程池和配置信息椎镣。
OkHttpClient eagerClient = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build();
Response response = eagerClient.newCall(request).execute();
- 每一個Call(其實現(xiàn)是RealCall)只能執(zhí)行一次,否則會報異常兽赁,具體參見
RealCall#execute()