我正在使用Spring Boot和restTemplate来使用RESTful Web服务。该服务以2路ssl保护。所以我已经制作了这个代码来配置连接。代码可以工作,但我正在寻找的是使用spring restTemplate和httpClient或使用Spring Boot的另一种替代方法实现2路SSL的最佳方法
@Configuration()
public class RestClientConfig {
private static final Logger log = LoggerFactory.getLogger(RestClientConfig.class);
@Bean()
@Qualifier("SSLRestOperations")
public RestOperations restOperations(ClientHttpRequestFactory clientHttpRequestFactory) throws Exception {
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
// timeout
requestFactory.setReadTimeout(60 * 1000);
requestFactory.setConnectTimeout(60 * 1000);
return requestFactory;
}
@Bean
public HttpClient httpClient(@Value("${keystore.file}") Resource file, @Value("${keystore.pass}") Password password) throws Exception {
String keystorePassword = password.getDescrambled();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManagerFactory tmf =TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream instream = file.getInputStream();
InputStream instreamKey = file.getInputStream();
try {
keyStore.load(instreamKey, keystorePassword.toCharArray());
trustStore.load(instream, keystorePassword.toCharArray());
kmf.init(keyStore, keystorePassword.toCharArray());
tmf.init(trustStore);
} finally {
instream.close();
instreamKey.close();
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.loadKeyMaterial(trustStore, keystorePassword.toCharArray()).build();
SSLSocketFactory socketFactory = sslcontext.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2" }, null, new NoopHostnameVerifier());
return HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()) // HostnameVerifier NoopHostnameVerifier
.setSSLSocketFactory(sslsf)
.build();
}