輕鬆把玩HttpClient之配置ssl,採用繞過證書驗證明現https

上篇文章說道httpclient不能直接訪問https的資源,此次就來模擬一下環境,而後配置https測試一下。在前面的文章中,分享了一篇本身生成並在tomcat中配置ssl的文章《Tomcat配置SSL》,你們能夠據此來在本地配置https。我已經配置好了,效果是這樣滴:java

能夠看到已經信任該證書(顯示淺綠色小鎖),瀏覽器能夠正常訪問。如今咱們用代碼測試一下:瀏覽器

 

  1. public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException, HttpProcessException {  
  2.     String url = "https://sso.tgb.com:8443/cas/login";  
  3.     String body = send(url, null, "utf-8");  
  4.     System.out.println("交易響應結果:");  
  5.     System.out.println(body);  
  6.     System.out.println("-----------------------------------");  
  7. }  

 

 

發現拋出了異常,我知道的有兩種方案(也許還有我不知道的方案),這裏介紹第一種方案,也是用的比較多的方案——繞過證書驗證。直接看代碼吧:tomcat

 

  1. /** 
  2.  * 繞過驗證 
  3.  *   
  4.  * @return 
  5.  * @throws NoSuchAlgorithmException  
  6.  * @throws KeyManagementException  
  7.  */  
  8. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {  
  9.     SSLContext sc = SSLContext.getInstance("SSLv3");  
  10.   
  11.     // 實現一個X509TrustManager接口,用於繞過驗證,不用修改裏面的方法  
  12.     X509TrustManager trustManager = new X509TrustManager() {  
  13.         @Override  
  14.         public void checkClientTrusted(  
  15.                 java.security.cert.X509Certificate[] paramArrayOfX509Certificate,  
  16.                 String paramString) throws CertificateException {  
  17.         }  
  18.   
  19.         @Override  
  20.         public void checkServerTrusted(  
  21.                 java.security.cert.X509Certificate[] paramArrayOfX509Certificate,  
  22.                 String paramString) throws CertificateException {  
  23.         }  
  24.   
  25.         @Override  
  26.         public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
  27.             return null;  
  28.         }  
  29.     };  
  30.   
  31.     sc.init(null, new TrustManager[] { trustManager }, null);  
  32.     return sc;  
  33. }  

而後修改原來的send方法:app

  1. /** 
  2.  * 模擬請求 
  3.  *  
  4.  * @param url       資源地址 
  5.  * @param map   參數列表 
  6.  * @param encoding  編碼 
  7.  * @return 
  8.  * @throws NoSuchAlgorithmException  
  9.  * @throws KeyManagementException  
  10.  * @throws IOException  
  11.  * @throws ClientProtocolException  
  12.  */  
  13. public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {  
  14.     String body = "";  
  15.     //採用繞過驗證的方式處理https請求  
  16.     SSLContext sslcontext = createIgnoreVerifySSL();  
  17.       
  18.        // 設置協議http和https對應的處理socket連接工廠的對象  
  19.        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
  20.            .register("http", PlainConnectionSocketFactory.INSTANCE)  
  21.            .register("https", new SSLConnectionSocketFactory(sslcontext))  
  22.            .build();  
  23.        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  24.        HttpClients.custom().setConnectionManager(connManager);  
  25.   
  26.        //建立自定義的httpclient對象  
  27.     CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();  
  28. /       CloseableHttpClient client = HttpClients.createDefault();  
  29.       
  30.     //建立post方式請求對象  
  31.     HttpPost httpPost = new HttpPost(url);  
  32.       
  33.     //裝填參數  
  34.     List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
  35.     if(map!=null){  
  36.         for (Entry<String, String> entry : map.entrySet()) {  
  37.             nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  38.         }  
  39.     }  
  40.     //設置參數到請求對象中  
  41.     httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));  
  42.   
  43.     System.out.println("請求地址:"+url);  
  44.     System.out.println("請求參數:"+nvps.toString());  
  45.       
  46.     //設置header信息  
  47.     //指定報文頭【Content-type】、【User-Agent】  
  48.     httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");  
  49.     httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  50.       
  51.     //執行請求操做,並拿到結果(同步阻塞)  
  52.     CloseableHttpResponse response = client.execute(httpPost);  
  53.     //獲取結果實體  
  54.     HttpEntity entity = response.getEntity();  
  55.     if (entity != null) {  
  56.         //按指定編碼轉換結果實體爲String類型  
  57.         body = EntityUtils.toString(entity, encoding);  
  58.     }  
  59.     EntityUtils.consume(entity);  
  60.     //釋放連接  
  61.     response.close();  
  62.        return body;  
  63. }  

 

如今再進行測試,發現果真通了。socket

 

 

下篇介紹另外一種方案,應對本身生成的證書,敬請期待。ide

 

 

轉自 http://blog.csdn.net/xiaoxian8023post

相關文章
相關標籤/搜索