• 如何访问https的网站?-【httpclient】


    备注:本处代码使用groovyhttpclient4.3作为例子进行讲述

     

    在普通方式下,当使用httpclient进行访问某个网站时,大致使用如下的代码进行访问:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    
    HttpGet httpMethod = new HttpGet(url);
    
    response = httpclient.execute(httpMethod);

    当使用上述代码来访问https的网站时,就会抛出如下的异常:

     

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

     

     

     

    要解决此问题,可以通过如下的方式:

     

    首先创建一个类DefaultTrustManager

     

    class DefaultTrustManager implements X509TrustManager{
        @Override
        void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
        }
    
        @Override
        void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
        }
    
        @Override
        X509Certificate[] getAcceptedIssuers() {
            return null
        }
    }

     

    然后在创建httpclient时,使用如下的代码:

     

    def trustManagers =  new TrustManager[1]
    trustManagers[0] = new DefaultTrustManager()
    
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
    SSLContext.setDefault(sslContext);
    
    sslContext.init(null, trustManagers, null);
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();

    这样在访问某些https的网站时就能正常访问了。

     

  • 相关阅读:
    CentOS 下实现两台服务器之间的共享NFS
    CentOS 下安装无线哥的老爷机DELL的无线驱动
    PHP 如何读取一个1G的文件大小
    php 经典的算法题你懂的
    mongodb与mysql命令对比
    TCP协议的三次握手和四次挥手过程
    java 发送带Basic Auth认证的http post请求实例代码
    HTTP基本认证(Basic Authentication)的JAVA实例代码
    Http协议
    MySQL主从同步那点事儿
  • 原文地址:https://www.cnblogs.com/dreampursuer/p/3488662.html
Copyright © 2020-2023  润新知