HttpClient4.2.X绕过SSL验证实现https请求

HttpClient4.2.X绕过SSL验证实现https请求

之前写过Httpclient4.5.X绕过SSL验证实现https请求,今天又遇到了这个问题,把代码复制过去发现有些类没有,这是版本升级后新增的一些类旧版本没有。项目中httpclient版本4.2.6,理论上4.2.X都适用,如果版本不对就不用往下看了。


  • 创建一个SSLClient类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package cn.pconline.activity.util;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
* 继承DefaultHttpClient
* 创建的SSLClient对象发送https 请求,绕过java的证书信任检查
*/
public class SSLClient extends DefaultHttpClient {
//用于进行Https请求的HttpClient
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException { }
@Override
public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException { }
@Override
public X509Certificate[] getAcceptedIssuers() {return null; }
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
  • HttpClient创建方法
1
2
3
4
5
6
7
8
9
10
11
12
13
// HttpGet
HttpClient httpClient = new SSLClient(); //这里使用自己创建的类
HttpGet httpGet = new HttpGet("https://www.gridsum.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
String result = null;
if (httpResponse != null) {
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}

// HttpPost和上面使用方法一样

参考文档:

https://www.jianshu.com/p/637ca9a44b28

-------------已经触及底线 感谢您的阅读-------------

本文标题:HttpClient4.2.X绕过SSL验证实现https请求

文章作者:趙小傑~~

发布时间:2019年11月08日 - 17:19:09

最后更新:2019年11月28日 - 22:04:51

原始链接:https://cnsyear.com/posts/c01fe57d.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%