Okhttp3 簡單使用(1)
- Okhttp3 是一個搞笑的HTTP 客戶端
- 支持HTTP/2,允許所有同一個主機地址的請求共享同一個socket連接;
- 連接池減少請求延時,降低資源消耗;
- 透明的GZIP壓縮減少響應數據的大小;
- 緩存響應內容,避免一些完全重複的請求;
基本使用
- 構建 OkHttpClient 對象;
- 構建 Request 對象
- 通過 OkHttpClient 和 Request 來構建 Call 對象;
- 調用Call 對象的方法提交請求;
使用案例代碼
public class OkHttpClientUtils {
private static int connTimeOut = 5;
private static int readTimeOut = 20;
private static int writeTimeOut = 10;
public static OkHttpClient client = null;
static {
client = new OkHttpClient.Builder()
.connectTimeout(connTimeOut, TimeUnit.SECONDS)
.readTimeout(readTimeOut, TimeUnit.SECONDS)
.writeTimeout(writeTimeOut, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.connectionPool(new ConnectionPool())
.build();
}
public OkHttpClientUtils() {
}
public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
if (!CollectionUtils.isEmpty(params)) {
String paramStr = DexUtils.mapToString(params);
url = url + "?" + paramStr;
}
Request.Builder requestBuilder = new Request.Builder();
if (!CollectionUtils.isEmpty(headers)) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
requestBuilder.addHeader(key, headers.get(key));
}
}
Request request = requestBuilder.get()
.url(url)
.build();
Response response = client.newCall(request).execute();
String responseStr = response.body() == null ? "" : response.body().string();
return responseStr;
}
}
- 以上是簡單的封裝了一個get 請求,同理可以封裝post 請求
部分源碼
public Builder() {
this.dispatcher = new Dispatcher();
this.protocols = OkHttpClient.DEFAULT_PROTOCOLS;
this.connectionSpecs = OkHttpClient.DEFAULT_CONNECTION_SPECS;
this.proxySelector = ProxySelector.getDefault();
this.cookieJar = CookieJar.NO_COOKIES;
this.socketFactory = SocketFactory.getDefault();
this.hostnameVerifier = OkHostnameVerifier.INSTANCE;
this.certificatePinner = CertificatePinner.DEFAULT;
this.proxyAuthenticator = Authenticator.NONE;
this.authenticator = Authenticator.NONE;
this.connectionPool = new ConnectionPool();
this.dns = Dns.SYSTEM;
this.followSslRedirects = true;
this.followRedirects = true;
this.retryOnConnectionFailure = true;
this.connectTimeout = 10000;
this.readTimeout = 10000;
this.writeTimeout = 10000;
this.pingInterval = 0;
}
Request(Request.Builder builder) {
this.url = builder.url;
this.method = builder.method;
this.headers = builder.headers.build();
this.body = builder.body;
this.tag = builder.tag != null ? builder.tag : this;
}
PS
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(Constant.URL).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
try {
res = response.body().string();
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
Log.d(TAG, res);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
});