java - 使用 restTemplate 时需要忽略证书

标签 java spring-mvc ssl resttemplate

我正在尝试向以下地址发送请求。证书无效,我想忽略它。我根据对 1 的研究编写了以下代码, 2但我无法完成它。我正在使用 Java 1.7,

https://api.stubhubsandbox.com/search/catalog/events/v3

代码

private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers(){
            return null;
        }
        public void checkClientTrusted( X509Certificate[] certs, String authType ){}
        public void checkServerTrusted( X509Certificate[] certs, String authType ){}
        public void checkClientTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
        public void checkServerTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
    }
};

public static void main(String[] args) {
    TrustStrategy acceptingTrustStrategy = 

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(csf)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    RestTemplate restTemplate = new RestTemplate(requestFactory);
    String url = "https://api.stubhubsandbox.com/search/catalog/events/v3";
    RestTemplate rest = new RestTemplate();
    Map<String, String> mvm = new HashMap<String, String>();
    mvm.put("Authorization", "Bearer TOKEEEEEEEN");
    Object object = rest.postForObject(url, null, Object.class, mvm);
    System.err.println("done");


}

最佳答案

您可能已经注意到,Spring 的 RestTemplate 将所有与 HTTP(S) 相关的内容委托(delegate)给 ClientHttpRequestFactory 的底层实现。由于您使用的是基于 HttpClient 的实现,因此这里有一些有用的 SO 链接,说明如何为内部 HttpClient 实现此目的:

显然,从 4.4 版开始,这可以按以下方式完成:

CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();

关于java - 使用 restTemplate 时需要忽略证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672803/

相关文章:

java - spring MVC 可以在没有应用服务器的情况下运行吗?

java - Rest url 中查询参数的日期时间格式

php - Drupal 8 curl 60 错误

java - 尝试调试 hibernate/c3p0/postgres 设置

java - 安卓工作室 : debug application on device

java - JSP/Liferay 的 Jquery 进度条实现

spring - 注释为 ResponseStatus 的自定义异常的动态消息

PUT 和 DELETE 方法中的 WCF REST 错误 401.3 但 GET 和 POST 中没有

ssl - 简单的 Akka ssl 加密

java - JDK动态代理