springboot设置RestTemplate支持http&https

发布于:2024-04-09 ⋅ 阅读:(99) ⋅ 点赞:(0)

1.添加HttpsClientRequestFactory

public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected 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 {

    @Bean
    public RestTemplate restTemplate() {
        HttpsClientRequestFactory factory = new HttpsClientRequestFactory();
        //单位为ms (部分接口数据量大,读取改为60秒)
        factory.setReadTimeout(60000);
        //单位为ms
        factory.setConnectTimeout(10000);
        return new RestTemplate(factory);
    }

}

之后在使用的地方注入就行了