RestTemplate是Spring提供的用于访问Rest服务的客户端,提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。RestTemplate 默认使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接(SimpleClientHttpRequestFactory),不需要配置证书信息,但如果调用https请求时的证书不合法,会报”unable to find valid certification path to requested target“错误。这时可以使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务来配置证书。

代码如下:

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component("httpClientFactory")
public class HttpClientFactory { @Value("${restclient.readTimeout}")
private int readTimeout; @Value("${restclient.connectTimeout}")
private int connectTimeout; public CloseableHttpClient acceptsUntrustedCertsHttpClient() throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException {
SSLContext sslcontext = SSLContexts.custom().setSecureRandom(new SecureRandom())
.loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout).setStaleConnectionCheckEnabled(true).build(); return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();
}
}

初始化httpClient

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="httpClient" factory-bean="httpClientFactory" 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 index="0">
<list>
<bean id="byteArrayHttpMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"></constructor-arg>
</bean>
<bean id="resourceHttpMessageConverter" class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
<bean id="sourceHttpMessageConverter" class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
<bean id="allEncompassingFormHttpMessageConverter" class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"></bean>
</list>
</constructor-arg>
<property name="requestFactory" ref="clientHttpRequestFactory" />
</bean>
</beans>

配置resttemplate

最新文章

  1. linux下的shell运算(加、减、乘、除)
  2. 论文笔记之: Deep Metric Learning via Lifted Structured Feature Embedding
  3. java_常用数据类型转换基础篇
  4. JVM学习总结五(番外)——VisualVM
  5. Mybatis批量插入oracle,mysql
  6. C++的优秀特性5:模版
  7. iOS 10 推送必看(高阶1)
  8. 同时安装vs2010和VS2012后IEnumerable&lt;ModelClientValidationRule&gt;编译错误
  9. Windows坐标系
  10. Ubuntu14.04配置arm-linux-gcc 4.4.3交叉编译环境
  11. [转载] python利用psutil遍历进程名字和exe所在目录
  12. ThinkPHP3.2 实现Mysql数据库备份
  13. 小强的HTML5移动开发之路(9)——坦克大战游戏3
  14. &#127827; 移动端调试工具之vconsole的使用~ &#127827;
  15. 【java】多态
  16. oo第12次作业
  17. Postgresql的隐藏系统列
  18. 云服务器 linux文件系统异常an error occurren during the file system check导致服务器启动失败
  19. iOS 两个应用之间的切换
  20. 子类化QTreeWidgetItem实现增加Item的属性

热门文章

  1. Android ListView工作原理完全解析(转自 郭霖老师博客)
  2. testng日志 ITestListener
  3. Python(异常处理)
  4. Full List of NMD R1 Singapore 2017
  5. SQL Server 使用 Pivot 和 UnPivot 实现行列转换
  6. 开发者应该了解的API技术清单
  7. centos升级vim
  8. 怎么解决teamviewer检测商业用途无法使用的问题
  9. C++通过HTTP请求Get或Post方式请求Json数据(转)
  10. lvds split两channel输出到一个屏显示