加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:08:15 所属栏目:Java 来源:网络整理
导读:我正在向以下地址发送请求.证书无效,我想忽略它.我根据我在 1,2的研究写了以下代码,但是我无法完成.我正在使用Java 1.7, https://api.stubhubsandbox.com/search/catalog/events/v3 码 private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = n
我正在向以下地址发送请求.证书无效,我想忽略它.我根据我在 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)相关的内容委托给ClientHttpRequestFactory的底层实现.由于您使用基于HttpClient的实现,以下是有关如何为内部HttpClient实现此功能的几个有用的SO链接:

> Ignoring SSL certificate in Apache HttpClient 4.3
> How to ignore SSL certificate errors in Apache HttpClient 4.0

显然,自4.4版以来,可以这样做:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读