SpringBoot 集成 okhttp3
okhttp3 一些常用操作方式 & 一点源码解析。
前言
为什么要用 okhttp3
?
因为:OkHttpClient
绝对线程安全,而且 JVM
全局共享一个 OkHttpClient
,性能更好~
SpringBoot 集成 okhttp3
Maven
导入 jar
包,具体版本根据自己需求来,在此只是举例:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0-RC1</version>
</dependency>
配置代码如下:
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OkHttp3Configuration {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES))
.retryOnConnectionFailure(false)
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
.addInterceptor(chain -> {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.header("test", "test")
.build();
return chain.proceed(requestWithUserAgent);
}).build();
}
@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
//信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
}
常规操作
- Get
- Post
- Put
- Delete
Request request = new Request.Builder().url(url).get().build();
Request request = new Request.Builder().url(url).method("GET", null).build();
Request request = new Request.Builder().url(url).post().build();
Request request = new Request.Builder().url(url).put().build();
Request request = new Request.Builder().url(url).delete().build();
自定义 Header
Map<String, String> headerMap = Maps.newHashMap();
headerMap.put("Content-Type","application/json");
Headers header = Headers.of(headerMap);
Request request = new Request.Builder().headers(header).url(url).get().build();
FormBody
RequestBody formBody = new FormBody.Builder()
.add("test1", "1")
.add("test2", "2")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
发送 JSON 数据
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder().url(url).post(requestBody).build();
发送 XML 数据
RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
Request request = new Request.Builder().url(url).post(requestBody).build();
同步请求
Request request = new Request.Builder().url("http://www.baidu.com").get().build();
try (Response response = client.newCall(request).execute()) {
log.info("{}", response.body().string());
}
异步请求
Request request = new Request.Builder().url("http://blog.sonicshield.cn").get().build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
log.info("{}", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
log.info("{}", response.body().string());
}
}
});
扩展阅读
Call
Call
是一个接口,定义了各种 Http
连接请求的方法
public interface Call extends Cloneable {
Request request();
Response execute() throws IOException;
void enqueue(Callback var1);
void cancel();
boolean isExecuted();
boolean isCanceled();
Call clone();
public interface Factory {
Call newCall(Request var1);
}
}
通过 request()
方法获取自己的请求体,调用 enqueue
发起异步请求,调用 execute
发起同步请求。
RealCall
RealCall
则是 Call
的实现类,其中实现了 execute
和 enqueue
等方法。而在 RealCall
的 execute
和 enqueue
方法中都调用到了 dispatcher.enqueue / execute
同步方法 RealCall.execute
public Response execute() throws IOException {
synchronized(this) {
if (this.executed) {
throw new IllegalStateException("Already Executed");
}
this.executed = true;
}
this.captureCallStackTrace();
Response var2;
try {
this.client.dispatcher().executed(this);
Response result = this.getResponseWithInterceptorChain();
if (result == null) {
throw new IOException("Canceled");
}
var2 = result;
} finally {
this.client.dispatcher().finished(this);
}
return var2;
}
- 检查这个
call
是否已经被执行了,每个call
只能被执行一次 - 实际执行代码
client.dispatcher().executed(this)
,dispatcher
(调度器,里面包含了线程池和三个队列(readyAsyncCalls:保存等待执行的异步请求) - 调用
getResponseWithInterceptorChain()
函数获取HTTP
返回结果,从函数名可以看出,这一步还会进行一系列 “拦截” 操作,可以配置拦截器 - 最后还要通知
dispatcher
已经执行完毕
实际真正发出网络请求,解析返回结果的是 getResponseWithInterceptorChain
异步方法 RealCall.enqueue
public void enqueue(Callback responseCallback) {
synchronized(this) {
if (this.executed) {
throw new IllegalStateException("Already Executed");
}
this.executed = true;
}
this.captureCallStackTrace();
this.client.dispatcher().enqueue(new RealCall.AsyncCall(responseCallback));
}
查看代码 this.client.dispatcher().enqueue(new RealCall.AsyncCall(responseCallback));
实际是通过 AsyncCall
来实现异步
final class AsyncCall extends NamedRunnable {
private final Callback responseCallback;
AsyncCall(Callback responseCallback) {
super("OkHttp %s", new Object[]{RealCall.this.redactedUrl()});
this.responseCallback = responseCallback;
}
String host() {
return RealCall.this.originalRequest.url().host();
}
Request request() {
return RealCall.this.originalRequest;
}
RealCall get() {
return RealCall.this;
}
protected void execute() {
boolean signalledCallback = false;
try {
Response response = RealCall.this.getResponseWithInterceptorChain();
if (RealCall.this.retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback = true;
this.responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
this.responseCallback.onResponse(RealCall.this, response);
}
} catch (IOException var6) {
if (signalledCallback) {
Platform.get().log(4, "Callback failure for " + RealCall.this.toLoggableString(), var6);
} else {
this.responseCallback.onFailure(RealCall.this, var6);
}
} finally {
RealCall.this.client.dispatcher().finished(this);
}
}
}
AsyncCall
继承于NamedRunnable
,而NamaedRunnable
则实现了Runnable
方法AsyncCall
在线程池中,执行run
方法 ->execute
方法NamedRunnable
提供了一个抽象方法execute
,需要AsyncCall
实现,并会放在run
方法中执行
getResponseWithInterceptorChain
Response getResponseWithInterceptorChain() throws IOException {
List<Interceptor> interceptors = new ArrayList();
interceptors.addAll(this.client.interceptors());
// add 重定向拦截器
interceptors.add(this.retryAndFollowUpInterceptor);
// add 桥接拦截器
interceptors.add(new BridgeInterceptor(this.client.cookieJar()));
// add 缓存拦截器
interceptors.add(new CacheInterceptor(this.client.internalCache()));
// add 链接拦截器
interceptors.add(new ConnectInterceptor(this.client));
if (!this.forWebSocket) {
interceptors.addAll(this.client.networkInterceptors());
}
// add 读写拦截器(请求服务器拦截器)
interceptors.add(new CallServerInterceptor(this.forWebSocket));
Chain chain = new RealInterceptorChain(interceptors, (StreamAllocation)null, (HttpCodec)null, (RealConnection)null, 0, this.originalRequest);
// 执行链表拦截
return chain.proceed(this.originalRequest);
}
- 代码中添加了各种
interceptor
,并赋给了RealInterceptorChain
(拦截器链表) - 拦截器链表最终执行
RealInterceptorChain.proceed()
方法,去做一系列的网络拦截操作,最终获取到网络数据
最后修改于 2019-06-12
此篇文章的评论功能已经停用。