新旧apache HttpClient 获取httpClient方法
生活随笔
收集整理的這篇文章主要介紹了
新旧apache HttpClient 获取httpClient方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在apache?httpclient 4.3版本中對很多舊的類進行了deprecated標注,通常比較常用的就是下面兩個類了。
DefaultHttpClient —> CloseableHttpClient
HttpResponse —> CloseableHttpResponse
目前互聯網對外提供的接口通常都是HTTPS協議,有時候接口提供方所示用的證書會出現證書不受信任的提示,chrome訪問接口(通常也不會用chrome去訪問接口,只是舉個例子)會出現這樣的提示:
為此我們調用這類接口的時候就要忽略掉證書認證信息,我們調用接口的httpClient就要做特殊處理。下面記錄下httpclient 4.3以前和之后的httpClient獲取方法。
httpclient jar包4.3以前版本獲取HttpClient方法如下:
1 public static HttpClient getHttpClient(HttpClient base) { 2 try { 3 SSLContext ctx = SSLContext.getInstance("SSL"); 4 X509TrustManager tm = new X509TrustManager() { 5 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 6 return null; 7 } 8 9 @Override 10 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 11 } 12 13 @Override 14 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 15 } 16 }; 17 18 ctx.init(null, new TrustManager[] {tm}, null); 19 SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 20 ClientConnectionManager mgr = base.getConnectionManager(); 21 SchemeRegistry registry = mgr.getSchemeRegistry(); 22 registry.register(new Scheme("https", 443, ssf)); 23 return new DefaultHttpClient(mgr, base.getParams()); 24 } catch (Exception e) { 25 log.warn("{}", e); 26 return null; 27 } 28 }httpclient jar包4.3之后版本獲取HttpClient方法如下:
1 public static CloseableHttpClient getHttpClient() { 2 try { 3 SSLContext sslContext = SSLContext.getInstance("SSL"); 4 sslContext.init(null, new TrustManager[] {new X509TrustManager() { 5 @Override 6 public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { 7 8 } 9 10 @Override 11 public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { 12 13 } 14 15 @Override 16 public X509Certificate[] getAcceptedIssuers() { 17 return new X509Certificate[0]; 18 } 19 }}, new SecureRandom()); 20 SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); 21 CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build(); 22 return closeableHttpClient; 23 } catch (Exception e) { 24 log.warn("create closeable http client failed!"); 25 return HttpClientBuilder.create().build(); 26 } 27 }?
轉載于:https://www.cnblogs.com/snowater/p/7591128.html
總結
以上是生活随笔為你收集整理的新旧apache HttpClient 获取httpClient方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#应用视频教程3.1 USB工业相机测
- 下一篇: 经济学相关资料20170924.词袋.b