使用HttpClient4来构建Spring RestTemplate
Spring RestTemplate简单说明
现在REST服务已经很普及了,在我们的程序中,经常会需要调用REST API,这时候会有很多选择,原始一点的JDK自带的,再进一步点使用HttpClient,或者说如果我们使用Jersey这种框架的话,也会自带rest client。但是我们项目使用的SpringMVC,所以直接使用RestTemplate。使用RestTemplate比直接使用Httpclient简单很多,同时也可以借助httpclient来实现RestTemplate。
通过使用RestTemplate仅仅只需要写几行代码,就可以完成直接使用httpclient很多行代码的事情,具体见:https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate
RestTemplate有三个构造函数:
- 默认构造函数,默认使用SimpleClientHttpRequestFactory,使用JDK自带的java.net包进行网络传输。
- public RestTemplate(ClientHttpRequestFactory requestFactory)。传入一个ClientHttpRequestFactory,ClientHttpRequestFactory在Spring中的实现有很多个,如HttpComponentsClientHttpRequestFactory,Netty4ClientHttpRequestFactory等,具体的可以看代码,这里只介绍HttpComponentsClientHttpRequestFactory,需要用到 HttpClient4.
- public RestTemplate(List<HttpMessageConverter<?>> messageConverters),使用SpringMvc的应该对HttpMessageConverter很熟悉了,RestTemplate默认会给我们设置好常用的HttpMessageConverter,我一般很少使用到这个构造方法。
HttpComponentsClientHttpRequestFactory
这里主要讨论的是通过第二个构造方法来使用HttpClient4 来进行网络传输。下面我们来看下HttpComponentsClientHttpRequestFactory这个类。先看看他的构造方法
/**
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
* with a default {@link HttpClient}.
*/
public HttpComponentsClientHttpRequestFactory() {
this(HttpClients.createSystem());
}
/**
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
* with the given {@link HttpClient} instance.
* <p>As of Spring Framework 4.0, the given client is expected to be of type
* {@link CloseableHttpClient} (requiring HttpClient 4.3+).
* @param httpClient the HttpClient instance to use for this request factory
*/
public HttpComponentsClientHttpRequestFactory(HttpClient httpClient) {
Assert.notNull(httpClient, "'httpClient' must not be null");
Assert.isInstanceOf(CloseableHttpClient.class, httpClient, "'httpClient' is not of type CloseableHttpClient");
this.httpClient = (CloseableHttpClient) httpClient;
}
如果我们不指定一个HttpClient的话,会默认帮我们创建一个,如果我们程序调用比较频繁的话,为了提高性能,会考虑使用PoolingHttpClientConnectionManager来构建HttpClient,这时候就会使用到第二个。如何使用PoolingHttpClientConnectionManager来创建HttpClient呢?可以参考几个文章:http://www.yeetrack.com/?p=782 以及我前面的一篇:http://www.cnblogs.com/hupengcool/p/4554525.html ,这里就不具体讲了,可以网上搜索相关资料。
下面写写代码来描述下怎么通过HttpComponentsClientHttpRequestFactory来创建RestTemplate,为了方便创建HttpClient的代码我就直接使用我前面文章中的代码:
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Created by Administrator on 2015/6/8.
*/
public class HttpClientUtils {
public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClientBuilder b = HttpClientBuilder.create();
// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
// don't check Hostnames, either.
// -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
connMgr.setMaxTotal(200);
connMgr.setDefaultMaxPerRoute(100);
b.setConnectionManager( connMgr);
// finally, build the HttpClient;
// -- done!
CloseableHttpClient client = b.build();
return client;
}
}
创建并使用RestTemplate
CloseableHttpClient httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
String result = restTemplate.getForObject("http://www.baidu.com",String.class);
System.out.println(result);
那么问题来了,我们既然是使用Spring,那肯定希望把他RestTemplate配置成Spring bean来使用,HttpClient是线程安全的,他可以在程序中共享,创建一个成Spring bean刚好。下面是xml配置。
<bean id="httpClient" class="com.hupengcool.util.HttpClientUtils" factory-method="acceptsUntrustedCertsHttpClient"/>
<bean id="clientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
<bean id="restTemplate" class=" org.springframework.web.client.RestTemplate">
<constructor-arg ref="clientHttpRequestFactory" />
</bean>
开始使用Spring RestTemplate吧。。。。。
PS:项目中除了Spring相关jar包外。需要添加HttpClient4.5,jackson 2.x的jar包。
使用HttpClient4来构建Spring RestTemplate的更多相关文章
- Spring RestTemplate中几种常见的请求方式GET请求 POST请求 PUT请求 DELETE请求
Spring RestTemplate中几种常见的请求方式 原文地址: https://blog.csdn.net/u012702547/article/details/77917939 版权声明 ...
- SpringCloud核心教程 | 第二篇: 使用Intellij中的maven来快速构建Spring Cloud工程
spring cloud简介 spring cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理.服务发现.断路器.路由.微代理.事件总线.全局锁.决策竞选.分布式会话等等.它运行环 ...
- Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header
{ "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tom ...
- Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...
- Spring RestTemplate介绍
http://www.cnblogs.com/rollenholt/p/3894117.html RestTemplate 这篇文章打算介绍一下Spring的RestTemplate.我这边以前设计到 ...
- How to Send an HTTP Header With Every Request With Spring RestTemplate
In Know Which Apps Are Hitting Your Web Service, I showed how to write a servlet filter that enforce ...
- [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
Spring Boot——2分钟构建spring web mvc REST风格HelloWorld http://projects.spring.io/spring-boot/ http://spri ...
- Springboot(一):使用Intellij中的Spring Initializr来快速构建Spring Boot工程
使用Intellij中的Spring Initializr来快速构建Spring Boot工程 New---Project 可以看到图所示的创建功能窗口.其中Initial Service Url指向 ...
- Spring RestTemplate详解
Spring RestTemplate详解 1.什么是REST? REST(RepresentationalState Transfer)是Roy Fielding 提出的一个描述互联系统架构风格 ...
随机推荐
- 18软工实践-第八次作业(课堂实战)-项目UML设计(团队)
目录 团队信息 分工选择 课上分工 课下分工 ToDolist alpha版本要做的事情 燃尽图 UML 用例图 状态图 活动图 类图 部署图 实例图 对象图 时序图 包图 通信图 贡献分评定 课上贡 ...
- php addslashes和stripslashes函数
addslashes — 使用反斜线引用字符串 stripslashes — 反引用一个引用字符串 Example #1 一个 addslashes() 例子 <?php$str = &qu ...
- php 多维数组排序
PHP中array_multisort可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序. 关联(string)键名保持不变,但数字键名会被重新索引. 输入数组被当成一个表的列并以 ...
- (转) Elasticsearch 5.0 安装 Search Guard 5 插件
一.Search Guard 简介 Search Guard 是 Elasticsearch 的安全插件.它为后端系统(如LDAP或Kerberos)提供身份验证和授权,并向Elasticsearc ...
- javascript 分号理解
javascript自动填补分号的规则 在说要不要写分号之前,先了解一下javascript自动填补分号的规则. 在<javascript权威指南>中有一段话“如果一条语句以“(”.“[” ...
- react-router之代码分离
概念 无需用户下载整个应用之后才能访问访问它.即边访问边下载.因此我们设计一个组件<Bundle>当用户导航到它是来动态加载组件. import loadSomething from 'b ...
- Delphi 组件渐进开发浅谈(二)——双简合璧
2.双简合璧2.1.带有T[x]Label的T[x]Edit组件 请允许我用[x]的书写方式来表示不同的对象.因为随后将大量提及TLabeledEdit与TTntLabeledEdit.TCustom ...
- Spring mvc 数据验证框架注解
@AssertFalse 被注解的元素必须为false@AssertTrue 被注解的元素必须为false@DecimalMax(value) 被注解的元素必须为一个数字,其值必须小于等于指定的最小值 ...
- 【前端学习笔记01】JavaScript源生判断数据类型的方法
原始类型(值类型):Undefined.Null.Number.String.Boolean: 对象类型(引用类型):Object: typeof 可以识别标准类型,null外(返回Object): ...
- HDU4810_Wall Painting
题目很简单. 给你n个数,输出n个答案,第i个答案表示从n个数里取遍i个数的异或值的和. 其实每一个数最多也就32位,把所有的数分解,保存每一位总共有多少个1,最后要是这一位的异或结果为1,那么在所有 ...