I.簡(jiǎn)介
HTTP是現(xiàn)代應(yīng)用常用的一種交換數(shù)據(jù)和媒體的網(wǎng)絡(luò)方式,高效地使用HTTP能讓資源加載更快,節(jié)省帶寬。OkHttp是一個(gè)高效的HTTP客戶(hù)端,它有以下默認(rèn)特性:
- 支持HTTP/2孽文,允許所有同一個(gè)主機(jī)地址的請(qǐng)求共享同一個(gè)socket連接
- 連接池減少請(qǐng)求延時(shí)
- 透明的GZIP壓縮減少響應(yīng)數(shù)據(jù)的大小
- 緩存響應(yīng)內(nèi)容,避免一些完全重復(fù)的請(qǐng)求
當(dāng)網(wǎng)絡(luò)出現(xiàn)問(wèn)題的時(shí)候OkHttp依然堅(jiān)守自己的職責(zé)夺艰,它會(huì)自動(dòng)恢復(fù)一般的連接問(wèn)題芋哭,如果你的服務(wù)有多個(gè)IP地址,當(dāng)?shù)谝粋€(gè)IP請(qǐng)求失敗時(shí)郁副,OkHttp會(huì)交替嘗試你配置的其他IP减牺,OkHttp使用現(xiàn)代TLS技術(shù)(SNI, ALPN)初始化新的連接,當(dāng)握手失敗時(shí)會(huì)回退到TLS 1.0存谎。
note: OkHttp 支持 Android 2.3 及以上版本Android平臺(tái)拔疚, 對(duì)于 Java, JDK 1.7及以上.
對(duì)于Okhttp3的源碼閱讀預(yù)計(jì)會(huì)寫(xiě)3篇文章來(lái)總結(jié):
II.使用
OkHttp的使用是非常簡(jiǎn)單的. 它的請(qǐng)求/響應(yīng) API 使用構(gòu)造器模式builders來(lái)設(shè)計(jì)既荚,它支持阻塞式的同步請(qǐng)求和帶回調(diào)的異步請(qǐng)求稚失。
Download OkHttp3
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
當(dāng)你看到這的時(shí)候,可能最新的穩(wěn)定版已經(jīng)不是3.10.0
了恰聘,你需要移步官方GitHub來(lái)查看最新版本句各。 官方地址 https://github.com/square/okhttp,另外不要忘了在清單文件聲明訪問(wèn)Internet的權(quán)限晴叨,如果使用 DiskLruCache
凿宾,那還得聲明寫(xiě)外存的權(quán)限。
1.1. 異步GET請(qǐng)求
-new OkHttpClient;
-構(gòu)造Request對(duì)象兼蕊;
-通過(guò)前兩步中的對(duì)象構(gòu)建Call對(duì)象初厚;
-通過(guò)Call#enqueue(Callback)方法來(lái)提交異步請(qǐng)求;
String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默認(rèn)就是GET請(qǐng)求孙技,可以不寫(xiě)
.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ā)起的請(qǐng)求會(huì)被加入到 Dispatcher
中的 runningAsyncCalls
雙端隊(duì)列中通過(guò)線程池來(lái)執(zhí)行产禾。
1.2. 同步GET請(qǐng)求
前面幾個(gè)步驟和異步方式一樣排作,只是最后一部是通過(guò) Call#execute()
來(lái)提交請(qǐng)求,注意這種方式會(huì)阻塞調(diào)用線程下愈,所以在Android中應(yīng)放在子線程中執(zhí)行纽绍,否則有可能引起ANR異常蕾久,Android3.0
以后已經(jīng)不允許在主線程訪問(wèn)網(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對(duì)象時(shí),需要多構(gòu)造一個(gè)RequestBody對(duì)象僧著,用它來(lái)攜帶我們要提交的數(shù)據(jù)履因。在構(gòu)造 RequestBody
需要指定MediaType
,用于描述請(qǐng)求/響應(yīng) body
的內(nèi)容類(lè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());
}
});
提交表單時(shí),使用 RequestBody
的實(shí)現(xiàn)類(lèi)FormBody
來(lái)描述請(qǐng)求體皆怕,它可以攜帶一些經(jīng)過(guò)編碼的 key-value
請(qǐng)求體毅舆,鍵值對(duì)存儲(chǔ)在下面兩個(gè)集合中:
private final List<String> encodedNames;
private final List<String> encodedValues;
2.5. POST方式提交分塊請(qǐng)求
MultipartBody 可以構(gòu)建復(fù)雜的請(qǐng)求體,與HTML文件上傳形式兼容愈腾。多塊請(qǐng)求體中每塊請(qǐng)求都是一個(gè)請(qǐng)求體憋活,可以定義自己的請(qǐng)求頭。這些請(qǐng)求頭可以用來(lái)描述這塊請(qǐng)求虱黄,例如它的 Content-Disposition
悦即。如果 Content-Length
和 Content-Type
可用的話,他們會(huì)被自動(dòng)添加到請(qǐng)求頭中橱乱。
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的攔截器鏈可謂是其整個(gè)框架的精髓辜梳,用戶(hù)可傳入的 interceptor
分為兩類(lèi):
①一類(lèi)是全局的 interceptor
,該類(lèi) interceptor
在整個(gè)攔截器鏈中最早被調(diào)用泳叠,通過(guò) OkHttpClient.Builder#addInterceptor(Interceptor)
傳入作瞄;
②另外一類(lèi)是非網(wǎng)頁(yè)請(qǐng)求的 interceptor
,這類(lèi)攔截器只會(huì)在非網(wǎng)頁(yè)請(qǐng)求中被調(diào)用危纫,并且是在組裝完請(qǐng)求之后粉洼,真正發(fā)起網(wǎng)絡(luò)請(qǐng)求前被調(diào)用,所有的 interceptor
被保存在 List<Interceptor> interceptors
集合中叶摄,按照添加順序來(lái)逐個(gè)調(diào)用属韧,具體可參考 RealCall#getResponseWithInterceptorChain()
方法。通過(guò) OkHttpClient.Builder#addNetworkInterceptor(Interceptor)
傳入蛤吓;
這里舉一個(gè)簡(jiǎn)單的例子宵喂,例如有這樣一個(gè)需求,我要監(jiān)控App通過(guò) OkHttp
發(fā)出的所有原始請(qǐng)求会傲,以及整個(gè)請(qǐng)求所耗費(fèi)的時(shí)間锅棕,針對(duì)這樣的需求就可以使用第一類(lèi)全局的 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;
}
}
針對(duì)這個(gè)請(qǐng)求,打印出來(lái)的結(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
注意到一點(diǎn)是這個(gè)請(qǐng)求做了重定向裸燎,原始的 request url
是 http://www.publicobject.com/helloworld.tx
顾瞻,而響應(yīng)的 request url
是 https://publicobject.com/helloworld.txt
,這說(shuō)明一定發(fā)生了重定向德绿,但是做了幾次重定向其實(shí)我們這里是不知道的荷荤,要知道這些的話,可以使用 addNetworkInterceptor()
去做移稳。更多的關(guān)于 interceptor
的使用以及它們各自的優(yōu)缺點(diǎn)蕴纳,請(qǐng)移步OkHttp官方說(shuō)明文檔。
IV. 自定義dns服務(wù)
Okhttp默認(rèn)情況下使用的是系統(tǒng)
V.其他
- 推薦讓
OkHttpClient
保持單例个粱,用同一個(gè)OkHttpClient
實(shí)例來(lái)執(zhí)行你的所有請(qǐng)求古毛,因?yàn)槊恳粋€(gè)OkHttpClient
實(shí)例都擁有自己的連接池和線程池,重用這些資源可以減少延時(shí)和節(jié)省資源都许,如果為每個(gè)請(qǐng)求創(chuàng)建一個(gè)OkHttpClient
實(shí)例稻薇,顯然就是一種資源的浪費(fèi)。當(dāng)然胶征,也可以使用如下的方式來(lái)創(chuàng)建一個(gè)新的OkHttpClient
實(shí)例塞椎,它們共享連接池、線程池和配置信息弧烤。
OkHttpClient eagerClient = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build();
Response response = eagerClient.newCall(request).execute();
- 每一個(gè)Call(其實(shí)現(xiàn)是RealCall)只能執(zhí)行一次忱屑,否則會(huì)報(bào)異常,具體參見(jiàn)
RealCall#execute()
</article>