概述:
HTTP是現代應用常用的一種交換數據和媒體的網絡方式。高效地使用HTTP能讓資源加載更快,節省帶寬。
OkHttp是一個高效的HTTP客戶端,它有以特性:
- 支持HTTP/2,允許所有同一個主機地址的請求共享同一個socket連接
- 連接池可以減少請求延時(如果HTTP/2不可用)
- 透明的GZIP壓縮減少響應數據的大小
- 緩存響應內容,避免一些完全重複的請求
當網絡出現問題的時候OkHttp依然堅守自己的職責,它會自動恢復一般的連接問題,如果你的服務有多個IP地址,當第一個IP請求失敗時,OkHttp會交替嘗試你配置的其他IP。這對於IPv4+IPv6和託管在冗餘數據中心的服務是必要的,OkHttp使用現代TLS技術(SNI, ALPN)初始化新的連接,當握手失敗時會回退到TLS 1.0。
要求:
- note: OkHttp 支持 Android 2.3 及以上版本Android平臺, 對於 Java, JDK 1.7及以上.
二、 使用:
1 . 前期準備:
1.1 在build.gradle 中添加:
implementation ‘com.squareup.okhttp3:okhttp:3.12.0’
最新版本可到github上獲取: https://github.com/square/okhttp
1.2 在AndroidManifest.xml中開啓網絡請求權限:
<uses-permission android:name=“android.permission.INTERNET”/>
2. 示例
2.1 同步get請求:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
2.2 異步get請求:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.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());
}
});
2.3 同步post請求:
表面上比get多一個body體,就是在構造Request對象時,需要多構造一個RequestBody對象,用它來攜帶我們要提交的數據。在構造 RequestBody 需要指定MediaType,用於描述請求/響應 body 的內容類型。
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
2.4 異步post請求:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.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());
}
});
實踐:
請求結果: