package com.hshbic.cloudapp.thirdserver.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author jff
*
*/
public class HttpClientUtil {
private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/** 读取超时 */
private final static int SOCKET_TIMEOUT = 60000;
/** 连接超时 */
private final static int CONNECTION_TIMEOUT = 10000;
private final static int CONNECTION_REQUEST_TIMEOUT = 10000;
/** 每个HOST的最大连接数量 */
private final static int MAX_CONN_PRE_HOST = 20;
/** 连接池的最大连接数 */
private final static int MAX_CONN = 60;
private final static String JSON_CHARSET = "application/json; charset=UTF-8";
/**
*
* @param url
* @param headers
* @param jsonData
* @return
* @throws Exception
*/
public static String doPost(String url,Map<String,String> headers,String jsonData)throws Exception {
if(url==null){
throw new Exception("请求URL为空");
}
CloseableHttpClient httpClient = getHttpClient();
HttpEntity responseEntity = null;
HttpPost httppost = null;
CloseableHttpResponse response = null;
httppost = new HttpPost(url);
try{
httppost.addHeader(HttpHeaders.CONTENT_TYPE, JSON_CHARSET);
if (jsonData == null || jsonData.trim().length() <= 0) {
throw new Exception("请求body为空");
}
StringEntity stringEntity= new StringEntity(jsonData, "UTF-8");
httppost.setEntity(stringEntity);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httppost.addHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httppost);
responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
return EntityUtils.toString(responseEntity);
} else {
throw new Exception("请求响应异常。 StatusCode=" + statusCode);
}
}catch(Exception e){
logger.error("POST请求 url= " + url + " 异常信息:"
+ e);
throw new Exception("POST请求异常 url=" + url, e);
}finally{
if (httppost != null) {
httppost.releaseConnection();
}
if (responseEntity != null) {
try {
responseEntity.getContent().close();
} catch (IOException e) {
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
}
/**
*
* @param url
* @param headers
* @param requestParas 表单提交方式
* @return
* @throws Exception
*/
public static String doPost(String url,Map<String,String> headers,Map<String,String> requestParas)throws Exception {
if(url==null){
throw new Exception("请求URL为空");
}
CloseableHttpClient httpClient = getHttpClient();
HttpEntity responseEntity = null;
HttpPost httppost = null;
CloseableHttpResponse response = null;
httppost = new HttpPost(url);
try{
httppost.addHeader(HttpHeaders.CONTENT_TYPE, JSON_CHARSET);
List<NameValuePair> form = new ArrayList<>();
if(requestParas!=null&&requestParas.size()>0){
for(String key: requestParas.keySet()){
if(key!=null&&key.length()>0){
form.add(new BasicNameValuePair(key, requestParas.get(key)));
}
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);
httppost.setEntity(entity);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httppost.addHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httppost);
responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
return EntityUtils.toString(responseEntity);
} else {
throw new Exception("请求响应异常。 StatusCode=" + statusCode);
}
}catch(Exception e){
logger.error("POST请求 url= " + url + " 异常信息:"
+ e);
throw new Exception("POST请求异常 url=" + url, e);
}finally{
if (httppost != null) {
httppost.releaseConnection();
}
if (responseEntity != null) {
try {
responseEntity.getContent().close();
} catch (IOException e) {
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
}
/**
*
* @param url
* @param headers
* @return
* @throws Exception
*/
public static String doGet(String url,Map<String,String> headers)throws Exception {
if(url==null){
throw new Exception("请求URL为空");
}
CloseableHttpClient httpClient = getHttpClient();
HttpEntity responseEntity = null;
HttpGet httpGet = null;
CloseableHttpResponse response = null;
httpGet = new HttpGet(url);
try{
httpGet.addHeader(HttpHeaders.CONTENT_TYPE, JSON_CHARSET);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httpGet);
responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
//logger.info(String.valueOf(statusCode));
return EntityUtils.toString(responseEntity);
} else {
throw new Exception("请求响应异常。 StatusCode=" + statusCode);
}
}catch(Exception e){
logger.error("请求 url= " + url + " 异常信息:"
+ e);
throw new Exception("请求异常 url=" + url, e);
}finally{
if (httpGet != null) {
httpGet.releaseConnection();
}
if (responseEntity != null) {
try {
responseEntity.getContent().close();
} catch (IOException e) {
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
}
/**
* 初始化 CloseableHttpClient
* @return CloseableHttpClient对象
*/
public static CloseableHttpClient getHttpClient() {
PoolingHttpClientConnectionManager connManager = null;
RequestConfig requestConfig = null;
try {
SSLContext sslContext = SSLContexts.createSystemDefault();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext)).build();
connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connManager.setMaxTotal(MAX_CONN);
connManager.setDefaultMaxPerRoute(MAX_CONN_PRE_HOST);
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
} catch (Exception e) {
logger.error("初始化【PoolingHttpClientConnectionManager、RequestConfig】异常:" + e);
}
return HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(requestConfig).build();
}
}