问题
后端服务需要使用 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 https://dzone.com/articles/spring-xml-based-di-and-builder-pattern-1
Spring FactoryBean 应用
spring 集成 okhttp3 https://miaoxinwei.github.io/2017/04/21/spring-集成-okhttp3/
Class ConnectionPool http://square.github.io/okhttp/3.x/okhttp/
来源: http://www.jianshu.com/p/e360294e8e15