一、RestTemplate 简介
Spring RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率.
RestTemplate包含以下几个部分:
- HttpMessageConverter 对象转换器:将请求对象转换为具体的数据格式输出,例
入:Jaxb2RootElementHttpMessageConverterket提供对xml格式的输入输出支持 - ClientHttpRequestFactory HTTP请求工厂,默认是JDK的HttpURLConnection,
可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式 - ResponseErrorHandler 异常错误处理
- ClientHttpRequestInterceptor 请求拦截器
RestTemplate通过HttpEntity添加消息headers
二、springboot 通过RestTemplate实现https访问
import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
/**
* service相关配置
*
* @date 2017年3月1日
* @since 1.0.0
*/
@Configuration
public class ServiceConfigConfiguration {
@Autowired
sslProperties sslProperties ;
/**
* 访问SSL的Template
*
* @throws Exception
*/
@Bean("sslRestTemplate")
@Conditional(sslCondition.class)
public RestTemplate tmsRestTemplate() throws Exception {
//新建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
//判断证书文件地址是否存在
if (StringUtils.isNotEmpty(sslProperties.getKeyfile())) {
//在握手期间,如果URL的主机名和服务器的标识主机名不匹配,则验证机制可以回调此接口的实现
程序来确定是否应该允许此连接
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
//构建SSL-Socket链接工厂
SSLConnectionSocketFactory ssLSocketFactory = buildSSLSocketFactory("PKCS12",
sslProperties.getKeyfile(),sslProperties.getPassword(),
Lists.newArrayList("TLSv1"), true);
//Spring提供HttpComponentsClientHttpRequestFactory指定使用HttpClient作为底层实现创建 HTTP请求
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(
HttpClients.custom().setSSLSocketFactory(ssLSocketFactory).build()
);
//设置传递数据超时时长
httpRequestFactory.setReadTimeout(sslProperties.getTimeout());
//设置建立连接超时时长
httpRequestFactory.setConnectTimeout(sslProperties.getTimeout());
//设置获取连接超时时长
httpRequestFactory.setConnectionRequestTimeout(tmsProperties.getTimeout());
restTemplate.setRequestFactory(httpRequestFactory);
// 返回消息头也是text_html,消息格式是XML,添加新的message converter
Jaxb2RootElementHttpMessageConverter messageConverter = new Jaxb2RootElementHttpMessageConverter();
//设置message Converter支持的媒体类型
List<MediaType> finalMediaTypes = new ArrayList<>();
finalMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
finalMediaTypes.add(MediaType.TEXT_HTML);
messageConverter.setSupportedMediaTypes(finalMediaTypes);
restTemplate.setMessageConverters(Lists.newArrayList(messageConverter));
}
return restTemplate;
}
/**
* 构建SSLSocketFactory
*
* @param keyStoreType
* @param keyFilePath
* @param keyPassword
* @param sslProtocols
* @param auth 是否需要client默认相信不安全证书
* @return
* @throws Exception
*/
private SSLConnectionSocketFactory buildSSLSocketFactory(String keyStoreType, String keyFilePath,
String keyPassword, List<String> sslProtocols, boolean auth) throws Exception {
//证书管理器,指定证书及证书类型
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//KeyStore用于存放证书,创建对象时 指定交换数字证书的加密标准
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
InputStream inputStream = resourcePatternResolver.getResource(keyFilePath).getInputStream();
try {
//添加证书
keyStore.load(inputStream, keyPassword.toCharArray());
} finally {
inputStream.close();
}
keyManagerFactory.init(keyStore, keyPassword.toCharArray());
SSLContext sslContext = SSLContext.getInstance("SSL");
if (auth) {
// 设置信任证书(绕过TrustStore验证)
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager trustManager = new AuthX509TrustManager();
trustAllCerts[0] = trustManager;
sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
} else {
//加载证书材料,构建sslContext
sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, keyPassword.toCharArray()).build();
}
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, sslProtocols.toArray(new String[sslProtocols.size()]),
null,
new HostnameVerifier() {
// 这里不校验hostname
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
return sslConnectionSocketFactory;
}
}
AuthX509TrustManager 证书信任管理器类就是实现了接口X509TrustManager的类。可以自己实现该接口,信任我们指定的证书
public class AuthX509TrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。