具有自定义CloseableHttpClient的RestTemplateBuilder仍会抛出SSLPeerUnverifiedException

时间:2017-04-05 10:41:18

标签: java spring-boot apache-httpclient-4.x resttemplate

情况

我必须连接到具有自签名证书的测试服务器来测试应用程序。为此,我执行以下操作:

  1. 我使用Spring框架中的 RestTemplateBuilder 来创建 RestTemplate
  2. 我传递了自定义配置的 HttpClient ,应该忽略主机名验证。
  3. 问题

    尽管有自定义http客户端,我仍然得到 SSLPeerUnverifiedException 。有线索吗?

    代码

    负责配置RestTemplate的部分代码:

    public class RestTemplateForBasicAuth {
      private RestTemplateBuilder restTemplateBuilder;
    
      public RestTemplateForBasicAuth(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplateBuilder = restTemplateBuilder;
      }
    
      public RestTemplate getRestTemplate(String host) {
    
        // Initialize http client that does not complain on self signed certificate
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpHost httpHost = new HttpHost(host);
        final AuthHttpComponentsClientHttpRequestFactory requestFactory = new AuthHttpComponentsClientHttpRequestFactory(httpClient, httpHost, "user", "xxx");
        restTemplateBuilder.requestFactory(requestFactory);
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        restTemplateBuilder.messageConverters(messageConverter);
        return restTemplateBuilder.build();
      }
    }
    

1 个答案:

答案 0 :(得分:0)

你是否使用了Spring(Boot)中正确的Annotations?

至少如果它是Spring Boot应用程序,您必须使用@Configuration和方法getRestTemplate(...)注释@Bean