HttpPost忽略证书请求https

最近工作中需要和一个第三方公司进行https交互请求,但是对方的证书有一些问题,所以在发送请求的时候需要忽略证书验证。百度之后,发现已经有很多这方面的介绍,不过在使用其代码的时候总会有一些类不推荐使用了。下面是参考网上的常见方面并结合最新的官方API实现的一个最新方法(使用的主要jar包括httpclient-4.5.1.jar和httpcore-4.4.3.jar)。

[java]  view plain  copy
  1. public static List doPostByClient(String url, Map postData, Map header,  
  2.         String encoding, long connectionTimeout, long soTimeout,boolean isNoSSL)  
  3.         throws Exception {  
  4.   
  5.     CloseableHttpClient client = HttpClients.createDefault();  
  6.     if(isNoSSL)  
  7.     {  
  8.         client = (CloseableHttpClient)wrapClient(client);  
  9.     }  
  10.   
  11.     HttpPost httpPost = new HttpPost(url);  
  12.     RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) soTimeout).setConnectTimeout((int) connectionTimeout).build();//设置请求和传输超时时  
  13.     httpPost.setConfig(requestConfig);  
  14.   
  15.     // 头部请求信息  
  16.     if (header != null) {  
  17.         Set entrySet = header.entrySet();  
  18.         for (Iterator itor = entrySet.iterator(); itor.hasNext();) {  
  19.             Map.Entry entry = (Map.Entry) itor.next();  
  20.             httpPost.addHeader(entry.getKey().toString(), entry.getValue()  
  21.                     .toString());  
  22.         }  
  23.     }  
  24.   
  25.     List parameters = new ArrayList();  
  26.   
  27.     if (postData != null) {  
  28.   
  29.         Set entrySet = postData.entrySet();  
  30.   
  31.         for (Iterator itor = entrySet.iterator(); itor.hasNext();) {  
  32.   
  33.             Map.Entry entry = (Map.Entry) itor.next();  
  34.   
  35.             parameters.add(new BasicNameValuePair(  
  36.                     entry.getKey().toString(), entry.getValue() + ""));  
  37.   
  38.         }  
  39.   
  40.         // 创建UrlEncodedFormEntity对象  
  41.         UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(  
  42.                 parameters, encoding);  
  43.           
  44.         httpPost.setEntity(formEntiry);  
  45.     }  
  46.   
  47.     // 执行请求  
  48.   
  49.     HttpResponse response = client.execute(httpPost);  
  50.   
  51.     response.getStatusLine();  
  52.   
  53.     StatusLine status = response.getStatusLine();  
  54.   
  55.     int sc = status.getStatusCode();  
  56.   
  57.     if (sc != 200) {  
  58.         return null;  
  59.     }  
  60.   
  61.     HttpEntity entity = response.getEntity();  
  62.   
  63.     if (entity != null) {  
  64.   
  65.         InputStream is = entity.getContent();  
  66.   
  67.         BufferedReader bin = new BufferedReader(new InputStreamReader(is,  
  68.                 "utf-8"), 1024 * 1024);  
  69.         List result = new ArrayList();  
  70.         while (true) {  
  71.             String line = bin.readLine();  
  72.             if (line == null) {  
  73.                 break;  
  74.             } else {  
  75.                 result.add(line);  
  76.             }  
  77.         }  
  78.         return (result);  
  79.     } else {  
  80.         return null;  
  81.     }  
  82. }  
  83.   
  84. /** 
  85.  * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常 
  86.  * 不用导入SSL证书 
  87.  * @param base 
  88.  * @return 
  89.  */  
  90. public static HttpClient wrapClient(HttpClient base) {  
  91.     try {  
  92.         SSLContext ctx = SSLContext.getInstance("TLS");  
  93.         X509TrustManager tm = new X509TrustManager() {  
  94.             public X509Certificate[] getAcceptedIssuers() {  
  95.                 return null;  
  96.             }  
  97.   
  98.             public void checkClientTrusted(X509Certificate[] arg0,  
  99.                     String arg1) throws CertificateException {  
  100.             }  
  101.   
  102.             public void checkServerTrusted(X509Certificate[] arg0,  
  103.                     String arg1) throws CertificateException {  
  104.             }  
  105.         };  
  106.         ctx.init(nullnew TrustManager[] { tm }, null);  
  107.         SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,NoopHostnameVerifier.INSTANCE);  
  108.         CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();  
  109.         return httpclient;  
  110.     } catch (Exception ex) {  
  111.         ex.printStackTrace();  
  112.         return HttpClients.createDefault();  
  113.     }  
  114. }  
说明:其中wrapClient方法就是创建一个不进行正式验证的请求客户端对象。

参考文档:

1.http://www.th7.cn/Program/Java/201402/173791.shtml Https请求基本过程介绍;

2.http://blog.csdn.NET/kobejayandy/article/details/44284765 老版本Https请求的常见实现;

3.http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/CloseableHttpClient.html  Https请求使用类的最新官方API说明。

你可能感兴趣的:(java)