httpclient https请求跳过验证
1 /** 2 * https请求用 3 * 4 * @param ip 5 * @param port 6 * @return 7 */ 8 public static CloseableHttpClient getHttpsClient(String ip, int port) { 9 CloseableHttpClient httpclient = null; 10 11 try { 12 // 采用绕过验证的方式处理https请求 13 SSLContext sslcontext = createIgnoreVerifySSL(); 14 // 设置协议http和https对应的处理socket链接工厂的对象 15 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() 16 .register("http", PlainConnectionSocketFactory.INSTANCE) 17 .register("https", new SSLConnectionSocketFactory(sslcontext)).build(); 18 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( 19 socketFactoryRegistry); 20 21 CookieStore cookieStore = new BasicCookieStore(); 22 HttpClientContext localContext = HttpClientContext.create(); 23 localContext.setCookieStore(cookieStore); 24 25 httpclient = HttpClients.custom().setConnectionManager(connManager).build(); 26 27 if (ip != null && !"".equals(ip)) { 28 HttpHost proxy = new HttpHost(ip, port); 29 DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); 30 httpclient = HttpClients.custom().setConnectionManager(connManager).setRoutePlanner(routePlanner) 31 .build(); 32 } 33 } catch (KeyManagementException e) { 34 e.printStackTrace(); 35 } catch (NoSuchAlgorithmException e) { 36 e.printStackTrace(); 37 } 38 39 return httpclient; 40 } 41 42 /** 43 * 绕过验证 44 * 45 * @return 46 * @throws NoSuchAlgorithmException 47 * @throws KeyManagementException 48 */ 49 public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { 50 SSLContext sc = SSLContext.getInstance("SSLv3"); 51 52 // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 53 X509TrustManager trustManager = new X509TrustManager() { 54 @Override 55 public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, 56 String paramString) throws CertificateException { 57 } 58 59 @Override 60 public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, 61 String paramString) throws CertificateException { 62 } 63 64 @Override 65 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 66 return null; 67 } 68 }; 69 70 sc.init(null, new TrustManager[] { trustManager }, null); 71 return sc; 72 }