配置RestTemplate支持发送Https请求
小徐参加的产品最近有个需求,需要配置RestTemplate,使它支持发送https给另一个服务,下面是我的代码
/** * 构建支持忽略自签名证书的Restemplate的bean * @return 支持发起https请求的RestTemplate对象 * @throws KeyStoreException 证书异常 * @throws NoSuchAlgorithmException 加密算法不可用异常 * @throws KeyManagementException 密钥管理异常 */ @Bean("httpsTemplate") public RestTemplate createHttpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory( sslContext, new NoopHostnameVerifier()); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslFactory) .build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(3600000); factory.setReadTimeout(3600000); factory.setHttpClient(httpClient); return new RestTemplate(factory); }
上一篇:
Java架构师技术进阶路线图