您的位置:首页 > 理论基础 > 计算机网络

Https请求忽略证书验证最新实现

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

public static List doPostByClient(String url, Map<?, ?> postData, Map<?, ?> header,
String encoding, long connectionTimeout, long soTimeout,boolean isNoSSL)
throws Exception {

CloseableHttpClient client = HttpClients.createDefault();
if(isNoSSL)
{
client = (CloseableHttpClient)wrapClient(client);
}

HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) soTimeout).setConnectTimeout((int) connectionTimeout).build();//设置请求和传输超时时
httpPost.setConfig(requestConfig);

// 头部请求信息
if (header != null) {
Set<?> entrySet = header.entrySet();
for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
Map.Entry entry = (Map.Entry) itor.next();
httpPost.addHeader(entry.getKey().toString(), entry.getValue()
.toString());
}
}

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

if (postData != null) {

Set<?> entrySet = postData.entrySet();

for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {

Map.Entry entry = (Map.Entry) itor.next();

parameters.add(new BasicNameValuePair(
entry.getKey().toString(), entry.getValue() + ""));

}

// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(
parameters, encoding);

httpPost.setEntity(formEntiry);
}

// 执行请求

HttpResponse response = client.execute(httpPost);

response.getStatusLine();

StatusLine status = response.getStatusLine();

int sc = status.getStatusCode();

if (sc != 200) {
return null;
}

HttpEntity entity = response.getEntity();

if (entity != null) {

InputStream is = entity.getContent();

BufferedReader bin = new BufferedReader(new InputStreamReader(is,
"utf-8"), 1024 * 1024);
List result = new ArrayList();
while (true) {
String line = bin.readLine();
if (line == null) {
break;
} else {
result.add(line);
}
}
return (result);
} else {
return null;
}
}

/**
* 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
* 不用导入SSL证书
* @param base
* @return
*/
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
return httpclient;
} catch (Exception ex) {
ex.printStackTrace();
return HttpClients.createDefault();
}
}说明:其中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说明。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息