package com.common.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
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.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
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.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
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.entity.ContentType;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
private static final int MAX_TIMEOUT = 7000;
private static RequestConfig setRequestConfig() {
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
//首先设置全局的标准cookie策略
configBuilder.setCookieSpec(CookieSpecs.STANDARD_STRICT);
return configBuilder.build();
}
/**
* 发送 GET 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
*/
public static String doGet(String apiUrl, Map<String, Object> params) {
String result = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(apiUrl);
if(MapUtils.isNotEmpty(params)){
for (Map.Entry<String, Object> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(),entry.getValue().toString());
}
}
uriBuilder.setCharset(StandardCharsets.UTF_8);
HttpGet httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(setRequestConfig());
response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}finally{
HttpClientUtils.closeQuietly(httpclient);
}
return result;
}
/**
* 发送 POST 请求(HTTP),K-V形式
*
* @param apiUrl
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if(MapUtils.isNotEmpty(params)){
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue().toString());
pairList.add(pair);
}
}
HttpEntity entity = EntityBuilder.create().setParameters(pairList).setContentType(ContentType.create(URLEncodedUtils.CONTENT_TYPE, MIME.UTF8_CHARSET)).build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
httpStr = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
*
* @param apiUrl
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doPostSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(createSSLConnectionManager()).setDefaultRequestConfig(setRequestConfig()).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if(MapUtils.isNotEmpty(params)){
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue().toString());
pairList.add(pair);
}
}
httpPost.setEntity(EntityBuilder.create().setParameters(pairList).setContentType(ContentType.create(URLEncodedUtils.CONTENT_TYPE, MIME.UTF8_CHARSET)).build());
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, StandardCharsets.UTF_8);
EntityUtils.consumeQuietly(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 发送 SSL GET 请求(HTTPS),K-V形式
*
* @param apiUrl
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doGetSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(createSSLConnectionManager()).setDefaultRequestConfig(setRequestConfig()).build();
HttpGet httpget = new HttpGet();
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpget.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if(MapUtils.isNotEmpty(params)){
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue().toString());
pairList.add(pair);
}
}
URIBuilder uriBuilder = new URIBuilder(apiUrl);
uriBuilder.setParameters(pairList);
uriBuilder.setCharset(StandardCharsets.UTF_8);
httpget.setURI(uriBuilder.build());
response = httpClient.execute(httpget);
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, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
//文件上传
public static String httpUpload(String apiUrl, Map<String, byte[]> fileMap,Map<String, String> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPut = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setLaxMode();
for (Map.Entry<String, String> entry : params.entrySet()) {
mBuilder.addTextBody(entry.getKey(), entry.getValue());
}
try {
httpPut.setConfig(setRequestConfig());
if(fileMap != null && fileMap.size() > 0){
Iterator<Entry<String, byte[]>> fileIter = fileMap.entrySet().iterator();
while(fileIter.hasNext()){
Map.Entry<String, byte[]> fileEntry = fileIter.next();
mBuilder.addBinaryBody(fileEntry.getKey(), fileEntry.getValue());
}
}
httpPut.setEntity(mBuilder.build());
response = httpClient.execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static PoolingHttpClientConnectionManager createSSLConnectionManager() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy(){
@Override
public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier(){
@Override
public boolean verify(String paramString, SSLSession paramSSLSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http",PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
// 设置连接池
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max total connection to 200
connMgr.setMaxTotal(100);
// Increase default max connection per route to 20
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
connMgr.setValidateAfterInactivity(MAX_TIMEOUT);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(MAX_TIMEOUT).build();
connMgr.setDefaultSocketConfig(socketConfig);
return connMgr;
}
}
httpUtils
最新推荐文章于 2024-04-21 09:53:21 发布