在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了。

DefaultHttpClient —> CloseableHttpClient
HttpResponse —> CloseableHttpResponse

目前互联网对外提供的接口通常都是HTTPS协议,有时候接口提供方所示用的证书会出现证书不受信任的提示,chrome访问接口(通常也不会用chrome去访问接口,只是举个例子)会出现这样的提示:

新旧apache HttpClient 获取httpClient方法-LMLPHP

为此我们调用这类接口的时候就要忽略掉证书认证信息,我们调用接口的httpClient就要做特殊处理。下面记录下httpclient 4.3以前和之后的httpClient获取方法。

httpclient jar包4.3以前版本获取HttpClient方法如下:

 public static HttpClient getHttpClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("SSL");
X509TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
} @Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}; ctx.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager mgr = base.getConnectionManager();
SchemeRegistry registry = mgr.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(mgr, base.getParams());
} catch (Exception e) {
log.warn("{}", e);
return null;
}
}

httpclient jar包4.3之后版本获取HttpClient方法如下:

 public static CloseableHttpClient getHttpClient() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] {new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();
return closeableHttpClient;
} catch (Exception e) {
log.warn("create closeable http client failed!");
return HttpClientBuilder.create().build();
}
}
04-24 16:20
查看更多