前言
我们在做项目的时候经常需要用到HTTP请求,但是org.apache.http.client
不满足HTTPS的请求,这里我们需要经常封装自己的请求库
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
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 javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.liberate.core.constant.LiberateConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
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.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
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.conn.ssl.TrustStrategy;
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.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
@Slf4j
public final class HttpUtils {
public static final String HTTP_METHOD_GET = "GET";
public static final String HTTP_METHOD_POST = "POST";
public static final String HTTP_METHOD_PUT = "PUT";
public static final String HTTP_METHOD_DELETE = "DELETE";
private static final int DEFAULT_CONNECT_TIMEOUT = 5;
private static final int DEFAULT_READ_TIMEOUT = 30;
private static PoolingHttpClientConnectionManager connectionManager;
private static int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
private static int readTimeout = DEFAULT_READ_TIMEOUT;
private HttpClientTools() {
}
private static synchronized void init() {
if (connectionManager == null) {
try {
Registry<ConnectionSocketFactory> connectionSocketFactory = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(
new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
}).build(),
new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}))
.build();
connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactory);
} catch (Exception e) {
log.warn("HttpClientTools PoolingHttpClientConnectionManager with connectionSocketFactory init occur error");
e.printStackTrace();
connectionManager = new PoolingHttpClientConnectionManager();
}
connectionManager.setMaxTotal(LiberateConsts.MAX_CONN_TOTAL);
connectionManager.setDefaultMaxPerRoute(LiberateConsts.MAX_CONN_PER_ROUTE);
}
}
private static CloseableHttpClient getHttpClient() {
init();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout * 1000)
.setConnectTimeout(connectTimeout * 1000).setSocketTimeout(readTimeout * 1000).build();
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
.build();
}
/**
* 设置自定义超时策略
*
* @param connectTimeout
* @param readTimeout
*/
public static void setCustomTimeout(int connectTimeout, int readTimeout) {
HttpClientTools.connectTimeout = connectTimeout;
HttpClientTools.readTimeout = readTimeout;
}
/**
* POST请求
*
* @param url
* @param heads
* @param params
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static String post(String url, Map<String, String> heads, Map<String, String> params)
throws IllegalStateException, IOException {
return post(url, heads, params, "utf-8");
}
/**
* POST请求
*
* @param url
* @param heads
* @param params
* @param encoding
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static String post(String url, Map<String, String> heads, Map<String, String> params, String encoding)
throws IllegalStateException, IOException {
HttpPost httpPost = new HttpPost(url);
if (MapUtils.isNotEmpty(heads)) {
Iterator<String> it = heads.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
httpPost.addHeader(key, heads.get(key));
}
}
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
if (MapUtils.isNotEmpty(params)) {
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
list.add(new BasicNameValuePair(key, params.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(list, encoding));
}
return getResult(httpPost);
}
/**
*
* @param url
* @param body
* @throws IllegalStateException
* @throws IOException
*/
public static String post(String url, JSONObject body)
throws IllegalStateException, IOException {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity stringEntity = new StringEntity(body.toJSONString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
httpPost.setEntity(stringEntity);
return getResult(httpPost);
}
/**
* GET请求
*
* @param url
* @param heads
* @param params
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String get(String url, Map<String, String> heads, Map<String, String> params)
throws ClientProtocolException, IOException {
String p = null;
StringBuilder sb = new StringBuilder();
if (MapUtils.isNotEmpty(params)) {
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
sb.append(key).append("=").append(params.get(key)).append("&");
}
p = sb.substring(0, sb.length() - 1);
}
HttpGet httpGet = new HttpGet(url + (p == null ? "" : ("?" + p)));
if (MapUtils.isNotEmpty(heads)) {
for (Map.Entry<String, String> head : heads.entrySet()) {
httpGet.addHeader(head.getKey(), head.getValue());
}
}
return getResult(httpGet);
}
/**
* 处理Http请求
* @param request
* @return
* @throws IOException
*/
private static String getResult(HttpRequestBase request) throws IOException {
String result = StringUtils.EMPTY;
CloseableHttpClient httpClient = getHttpClient();
try(CloseableHttpResponse response = httpClient.execute(request)) {
// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
// long len = entity.getContentLength();// -1 表示长度未知
result = EntityUtils.toString(entity, "UTF-8");
response.close();
// httpClient.close();
}
} catch (ClientProtocolException e) {
log.error("getResult request ClientProtocolException", e);
} catch (IOException e) {
log.error("getResult request IOException", e);
} finally {
}
return result;
}
/**
* 判断异常是否是连接超时的异常
*
* @param ex
* @return
*/
public static boolean isTimeoutException(Exception ex) {
// 读取超时
if (ex instanceof SocketTimeoutException) {
return true;
}
// 连接超时
if (ex instanceof ConnectTimeoutException) {
return true;
}
// httpclient插件的连接超时异常
if (ex instanceof ConnectionPoolTimeoutException) {
return true;
}
if (ex instanceof SocketException) {
return true;
}
return false;
}
}
网友评论