忽略安全证书的resttemplate配置

IgnoreSSLRestTemplate

Posted by Molly on July 31, 2019
/*
 * Create a RestTemplate bean, using the RestTemplateBuilder
 * with trust all SSL certificates and SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
 * replaced for new apache httpclient to NoopHostnameVerifier.INSTANCE
 */



@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws NoSuchAlgorithmException, KeyManagementException {

    /*
     * Ignore untrusted certificates
     */
    TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
    };

    // Install the all-trusting trust manager
    SSLContext sslContext = SSLContext.getInstance("SSL");

    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    /*
     * Create an HttpClient that uses the custom SSLContext and do not verify cert hostname
     */
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build();


    HttpComponentsClientHttpRequestFactory customRequestFactory =
            new HttpComponentsClientHttpRequestFactory();

    customRequestFactory.setHttpClient(httpClient);

    /*
     * Create a RestTemplate that uses custom request factory
     */
     RestTemplate restTemplate = builder.requestFactory(customRequestFactory).build();
     //设置restTemplate编码
     restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(Charset.forName("UTF-8")));

     //处理resttemplate异常,让其能读取code和message
     restTemplate.setErrorHandler(new ThrowErrorHandler());

     List<ClientHttpRequestInterceptor> list = new ArrayList<ClientHttpRequestInterceptor>();

     list.add(new UserAgentInterceptor());

     restTemplate.setInterceptors(list);
    return restTemplate;
}