HttpClient4.3.3 https请求

http://stackoverflow.com/questions/7256955/java-sslexception-hostname-in-certificate-didnt-match


public static void test1(){
      String rs = "";
         HttpGet get = new HttpGet("https://www.gotosearch.info/?gws_rd=cr#safe=strict&q=httpclient4.3.3&btnK=Google+%E6%90%9C%E7%B4%A2") ;
        
         try {
             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                 //信任所有
                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                     return true;
                 }
             }).build();
             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
             CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build() ;
              rs = client.execute( get,  new BasicResponseHandler() ) ;
          } catch ( Exception e) {
            e.printStackTrace();
          }
         System.out.println( rs  );
  }


需要设置SSl放权权限验证策略。 一般不建议直接用SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER

或者自己实现验证的方法


-----------------------------------------------------------------------

The concern is we should not use ALLOW_ALL_HOSTNAME_VERIFIER.

How about I implement my own hostname verifier?

class MyHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier
{
    @Override
    public boolean verify(String host, SSLSession session) {
        String sslHost = session.getPeerHost();
        System.out.println("Host=" + host);
        System.out.println("SSL Host=" + sslHost);    
        if (host.equals(sslHost)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void verify(String host, SSLSocket ssl) throws IOException {
        String sslHost = ssl.getInetAddress().getHostName();
        System.out.println("Host=" + host);
        System.out.println("SSL Host=" + sslHost);    
        if (host.equals(sslHost)) {
            return;
        } else {
            throw new IOException("hostname in certificate didn't match: " + host + " != " + sslHost);
        }
    }

    @Override
    public void verify(String host, X509Certificate cert) throws SSLException {
        throw new SSLException("Hostname verification 1 not implemented");
    }

    @Override
    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        throw new SSLException("Hostname verification 2 not implemented");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值