问题
后端服务需要使用http客户端请求其他服务支持,项目中需要将HttpClient换成OKhttp,为啥要换OKhttp?这里不讨论这两者之间的优缺点。这篇文章主要关注与Spring传统xml配置方式集成Okhttp。 之前写过的一篇关于OKhttp3中的cookies文章,转眼就一年的时间了,时间过得真快。
步骤
OkhttpBuilder.java
自定义封装okhttp的构建类。
package com.xxx;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import java.util.concurrent.TimeUnit;
/**
* 自定义Ok http 构建类
*/
public class OkhttpBuilder {
private OkHttpClient.Builder builder = new OkHttpClient.Builder();
/**
* 连接池
*/
private ConnectionPool connectionPool;
/**
* 为新连接设置默认连接超时,单位毫秒
*/
private long connectTimeout = 10000;
/**
* 构建客户端
* @return okhttp client
*/
public OkHttpClient build(){
if (connectionPool != null) {
builder.connectionPool(connectionPool);
}
if (connectTimeout != 10000) {
builder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
}
return builder.build();
}
public ConnectionPool getConnectionPool() {
return connectionPool;
}
public void setConnectionPool(ConnectionPool connectionPool) {
this.connectionPool = connectionPool;
}
public long getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(long connectTimeout) {
this.connectTimeout = connectTimeout;
}
}
spring.xml
spring管理okhttp client,以及okhttp的构建者和连接池。
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
...
<!-- okhttp3 client -->
<bean id="okhttpConnectionPool" class="okhttp3.ConnectionPool"/>
<bean id="builder" class="com.xxx.OkhttpBuilder">
<property name="connectTimeout" value="100"/>
<property name="connectionPool" ref="okhttpConnectionPool"/>
</bean>
<bean id="okhttpClient" class="okhttp3.OkHttpClient" factory-bean="builder" factory-method="build"/>
...
</beans>
Controller
注入OKhttp client。
@Autowired
private OkHttpClient okhttpClient;
在控制器中使用:
Request request = new Request.Builder()
.url("https://www.google.com/ncr")
.addHeader("myheader", "hello header")
.get()
.build();
Response response = null;
try {
response = okhttpClient.newCall(request).execute();
response.body().string();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(response != null) {
response.close();
}
}
**Note:**一定要在finally
中关闭连接,释放资源。
感受
简单方便,上手容易。
参考: Spring XML-Based DI and Builder Pattern Spring FactoryBean应用 spring 集成 okhttp3 Class ConnectionPool