本文主要是介绍springboot设置RestTemplate支持httphttps,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.添加HttpsClientRequestFactory
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {@Overrideprotected void prepareConnection(HttpURLConnection connection, String httpMethod) {try {if (!(connection instanceof HttpsURLConnection)) {//http协议super.prepareConnection(connection, httpMethod);}if ((connection instanceof HttpsURLConnection)) {HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());httpsURLConnection.setHostnameVerifier((hostname, session) -> hostname.equals("localhost")); //本地调试忽略证书super.prepareConnection(httpsURLConnection, httpMethod);}} catch (Exception e) {e.printStackTrace();}}}
2.配置RestTemplateConfig
@Configuration
@Slf4j
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate() {HttpsClientRequestFactory factory = new HttpsClientRequestFactory();//单位为ms (部分接口数据量大,读取改为60秒)factory.setReadTimeout(60000);//单位为msfactory.setConnectTimeout(10000);return new RestTemplate(factory);}}
之后在使用的地方注入就行了
这篇关于springboot设置RestTemplate支持httphttps的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!