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();
}
}
}
});