包结构
|---src
|---commons-logging-1.1.1.jar
|---httpclient-4.5.jar
|---httpcore-4.4.1.jar
|---httpmime-4.5.jar
|---log4j-1.2.17.jar
|---slf4j-api-1.7.5.jar
|---lib
|---\com\zy\httpclient
|---HttpClientUtils.java
|---NetUtils.java
代码
HttpClientUtils.java
package com.zy.httpclient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
/**
*
* @author louiseliu
*
*/
public class HttpClientUtils{
private static final Logger logger = Logger.getLogger(HttpClientUtils.class);
//表示请求器是否已经做了初始化工作
private boolean hasInit = false;
//连接超时时间,默认10秒
private int socketTimeout = 10000;
//传输超时时间,默认30秒
private int connectTimeout = 30000;
//请求器的配置
private RequestConfig requestConfig;
//HTTP请求器
private CloseableHttpClient httpClient;
//本地的证书地址
private String certLocalPath;
//本地的证书密码
private String certPassword;
private static boolean useCert=false;
/**
*使用证书文件
* @throws IOException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(certLocalPath));//加载本地的证书进行https加密传输
try {
keyStore.load(instream, certPassword.toCharArray());//设置证书密码
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
@SuppressWarnings("deprecation")
//指定TLS版本
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"},null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//设置httpclient的SSLSocketFactory
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
hasInit = true;
}
/**
* 通过Https往API post xml数据
* @param url API地址
* @param xmlObj 要提交的XML数据对象
* @return API回包的实际数据
* @throws IOException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public String sendPost(String url, String postDataXML) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
if (useCert) {
if (!hasInit) {
init();
}
}
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(postEntity);
httpPost.setConfig(requestConfig);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
} catch (ConnectionPoolTimeoutException e) {
logger.info("http get throw ConnectionPoolTimeoutException(wait time out)");
} catch (ConnectTimeoutException e) {
logger.info("http get throw ConnectTimeoutException");
} catch (SocketTimeoutException e) {
logger.info("http get throw SocketTimeoutException");
} catch (Exception e) {
logger.info("http get throw Exception");
} finally {
httpPost.abort();
}
return result;
}
/**
* 设置连接超时时间
*
* @param socketTimeout 连接时长,默认10秒
*/
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
resetRequestConfig();
}
/**
* 设置传输超时时间
*
* @param connectTimeout 传输时长,默认30秒
*/
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
resetRequestConfig();
}
//连接超时时间,默认10秒
private void resetRequestConfig(){
requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
}
/**
* 允许商户自己做更高级更复杂的请求器配置
*
* @param requestConfig 设置HttpsRequest的请求器配置
*/
public void setRequestConfig(RequestConfig requestConfig) {
this.requestConfig = requestConfig;
}
/**
* 是否使用安全证书
*
* @param b 设置是否使用安全证书 默认为否
*/
public void setUsCert(boolean b){
useCert=b;
}
}
NetUtils.java
package com.zy.httpclient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
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.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
public class NetUtils {
private static final Logger logger = Logger.getLogger(NetUtils.class);
// 表示请求器是否已经做了初始化工作
private static boolean hasInit = false;
// 连接超时时间,默认10秒
private int socketTimeout = 10000;
// 传输超时时间,默认30秒
private int connectTimeout = 30000;
// 请求器的配置
private RequestConfig requestConfig= RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
// HTTP请求器
private static CloseableHttpClient httpClient;
// 本地的证书地址
private static String certLocalPath;
// 本地的证书密码
private static String certPassword;
@Test
public void jUnitTest() {
String sendGet = sendGet("http://www.baidu.com/",false);
System.out.println(sendGet);
}
/**
* 使用证书文件
*
* @throws IOException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private static void init() throws IOException, KeyStoreException,
UnrecoverableKeyException, NoSuchAlgorithmException,
KeyManagementException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(certLocalPath));// 加载本地的证书进行https加密传输
try {
keyStore.load(instream, certPassword.toCharArray());// 设置证书密码
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
@SuppressWarnings("deprecation")
// 指定TLS版本
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
// 设置httpclient的SSLSocketFactory
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
hasInit = true;
}
/**
* 发送post请求
* @param url 请求地址
* @param params 请求参数
* @param useCert 是否使用证书
* @return
*/
public String sendPost(String url,Mapparams, boolean useCert) {
String result=null;
CloseableHttpClient httpclient = null;
if (useCert) {//如果使用证书就初始化
if (hasInit) {
try {
init();
} catch (Exception e) {
e.printStackTrace();
logger.error("httpClient======init错误");
}
}
httpclient=httpClient;
}else {//不适用证书
// 创建默认的httpClient实例.
httpclient = HttpClients.createDefault();
}
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列
List formparams =getFormParams(params);
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
httppost.setConfig(requestConfig);//填写请求配置
// System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
if (entity != null) {
// 打印响应内容长度
// entity.getContentLength());
// 打印响应内容
result = EntityUtils.toString(entity);
}
}
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* // 创建参数队列
* @param params 参数的map
* @return
*/
private List getFormParams(Map params) {
List formparams = new ArrayList();
Set keySet = params.keySet();
for (Iterator it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = params.get(name);
formparams.add(new BasicNameValuePair(name, value));
}
return formparams;
}
/**
* get发出网络请求 get请求
*
* @param url
* 功能和操作
* @param map
* 请求的map
* @return 请求返回的数据
*/
public static String sendGet(String netPath, Map map,boolean useCert) {
String body = changeMapToBody(map);
netPath = netPath + "?" + body;
String result = sendGet(netPath,useCert);
return result;
}
/**
* get发出网络请求 get请求
*
* @param url
* 功能和操作
* @param body
* 要get的数据 String body = "accountSid=" + ACCOUNT_SID + "&to=" +
* tel + "&templateid=" + templateid + "¶m=" + param+
* createCommonParam();
* @return 请求返回的数据
*/
public static String sendGet(String netPath, String body,boolean useCert) {
netPath = netPath + "?" + body;
String result = sendGet(netPath,useCert);
return result;
}
/**
* 发送 get请求
*
* @param url
* 请求的地址
* @return
*/
public static String sendGet(String url,boolean useCert) {
String result=null;
CloseableHttpClient httpclient = null;
if (useCert) {//如果使用证书就初始化
if (hasInit) {
try {
init();
} catch (Exception e) {
e.printStackTrace();
logger.error("httpClient======init错误");
}
}
httpclient=httpClient;
}else {//不适用证书
// 创建默认的httpClient实例.
httpclient = HttpClients.createDefault();
}
try {
// 创建httpget.
HttpGet httpget = new HttpGet(url);
// System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// System.out.println("--------------------------------------");
// 响应状态
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
if (entity != null) {
// 打印响应内容长度
// System.out.println("Response content length: " +
// entity.getContentLength());
// 打印响应内容
result = EntityUtils.toString(entity);
// System.out.println("Response content:789 " + result);
}
}
// System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 上传文件
* @return
*/
public static String upload(String postUrl,String fileUrl,boolean useCert) {
String result=null;
CloseableHttpClient httpclient = null;
if (useCert) {//如果使用证书就初始化
if (hasInit) {
try {
init();
} catch (Exception e) {
e.printStackTrace();
logger.error("httpClient======init错误");
}
}
httpclient=httpClient;
}else {//不适用证书
// 创建默认的httpClient实例.
httpclient = HttpClients.createDefault();
}
try {
HttpPost httppost = new HttpPost(postUrl);
FileBody bin = new FileBody(new File(fileUrl));
StringBody comment = new StringBody("A binary file of some kind",
ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
if (resEntity != null) {
// 打印响应内容长度
// entity.getContentLength());
// 打印响应内容
result = EntityUtils.toString(resEntity);
}
}
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
logger.error("upload======"+e);
} catch (IOException e) {
e.printStackTrace();
logger.error("upload======"+e);
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("upload======"+e);
}
}
return result;
}
/**
* 将map请求参数格式化
*
* @param ParamsMap
* 请求的参数
* @return 格式化后的参数
*/
public static String changeMapToBody(Map ParamsMap) {
StringBuffer params = new StringBuffer();
// 组织请求参数
Iterator> it = ParamsMap.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry element = (Map.Entry) it.next();
params.append(element.getKey());
params.append("=");
params.append(element.getValue());
params.append("&");
}
if (params.length() > 0) {
params.deleteCharAt(params.length() - 1);
}
return params.toString();
}
}