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

或者自己实现验证的方法


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

0 down vote

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"); } }

你可能感兴趣的:(httpclient,https,ssl,sslexception)