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

httpClient发送https请求

2017-03-13 22:32 671 查看
httpclient版本:4.5.2

package com.maven.httpclient.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ssl.TrustStrategy;

public class HttpUitl {
private static PoolingHttpClientConnectionManager conMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;

static{
//设置连接池
conMgr = new PoolingHttpClientConnectionManager();
conMgr.setMaxTotal(100);
conMgr.setDefaultMaxPerRoute(conMgr.getMaxTotal());

RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(MAX_TIMEOUT);
configBuilder.setSocketTimeout(MAX_TIMEOUT);
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);

requestConfig = configBuilder.build();
}

/**
* 发送get请求
* @param url
* @param headers
* @param params
* @param isHttps
* @return
*/
public static String doGet(String url, Map<String, Object> headers, Map<String, Object> params,
boolean isHttps){
HttpResponse response = null;
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
if(params != null && !params.isEmpty()){
for(String key : params.keySet()){
if(i == 0){
param.append("?");
}else{
param.append("&");
}
param.append(key).append("=").append(params.get(key));
}
}
apiUrl += param;
System.out.println("ss:"+apiUrl);
String result = null;
CloseableHttpClient httpclient = null;
if(isHttps){
httpclient = createSSLClientDefault();
}else{
httpclient = HttpClients.createDefault();
}

HttpGet httpGet = new HttpGet(apiUrl);
if(headers != null && !headers.isEmpty()){
for(String key : headers.keySet()){
httpGet.setHeader(key, headers.get(key).toString());
}
}
try {
response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("执行状态码: " + statusCode);
HttpEntity entity = response.getEntity();
if(entity != null){
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(response != null){
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

public static String doPost(String apiUrl, Map<String, Object> headers, Map<String, Object> params,
boolean isHttps){
CloseableHttpClient httpclient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
httpPost.setConfig(requestConfig);

if(headers != null && !headers.isEmpty()){
for(String key : headers.keySet()){
httpPost.setHeader(key, headers.get(key).toString());
}
}

if(params != null && !params.isEmpty()){
List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for(Map.Entry<String, Object> entry : params.entrySet()){
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
}
try {
response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
return null;
}
HttpEntity entity = response.getEntity();
if(entity != null){
return null;
}
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}

return httpStr;
}

/**
* 创建SSL连接
* @return
*/
public static CloseableHttpClient createSSLClientDefault(){
try {
@SuppressWarnings("deprecation")
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}

}


在代码测试中发现发送HTTPS请求时会报一个异常:

# Exception in thread "main" javax.net.ssl.SSLException: hostname in certificate didn't match: <w03gca01a> != <localhost>
#     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:220)
#     at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54)


查找资料后,只要将创建SSL连接的

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);


修改成

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);


就可以了

参考网址:
http://blog.csdn.net/happylee6688/article/details/47148227 http://blog.csdn.net/liufang1991/article/details/51595952 http://blog.csdn.net/blue_jjw/article/details/8768624 http://jinnianshilongnian.iteye.com/blog/2089792 http://blog.csdn.net/jbgtwang/article/details/38303183
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java