hutool http请求优化连接时间


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
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.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
* 利用HttpClient进行post请求的工具类
*/
public class HttpClientUtils {

/**
* 定义编码格式 UTF-8
*/
public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";

/**
* 定义编码格式 GBK
*/
public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";

private static final String URL_PARAM_CONNECT_FLAG = "&";

private static final String EMPTY = "";

private static MultiThreadedHttpConnectionManager connectionManager = null;

private static int connectionTimeOut = 25000;

private static int socketTimeOut = 25000;

private static int maxConnectionPerHost = 20;

private static int maxTotalConnections = 20;

private static HttpClient client;
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param params 请求的查询参数,能够为null
* @param charset 字符集
* @param pretty 是否美化
* @return 返回请求响应的HTML
*/
public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//设置参数的字符集
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
//设置Http Post数据
if (params != null) {
//HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
//p.setParameter(entry.getKey(), entry.getValue());
method.setParameter(entry.getKey(), entry.getValue());
}
//method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (IOException e) {
logger.error("执行HTTP Post请求" + url + "时,发生异常!", e);
response = null;
} finally {
method.releaseConnection();
}
return String.valueOf(response);
}

/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param params 请求的查询参数,能够为null
* @param charset 字符集
* @param pretty 是否美化
* @return 返回请求响应的HTML
*/
public static String doPost2(String url, Map<String, Object> params, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//设置参数的字符集
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
//设置Http Post数据
if (params != null) {
//HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, Object> entry : params.entrySet()) {
//p.setParameter(entry.getKey(), entry.getValue());
method.setParameter(entry.getKey(), String.valueOf(entry.getValue()));
}
//method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (IOException e) {
logger.error("执行HTTP Post请求" + url + "时,发生异常!", e);
response = null;
} finally {
method.releaseConnection();
}
return String.valueOf(response);
}


/**
* GET方式提交数据
* @param url
* 待请求的URL
* @param params
* 要提交的数据
* @param enc
* 编码
* @return
* 响应结果
* @throws IOException
* IO异常
*/
public static String URLGet(String url, Map<String, String> params, String enc){

String response = EMPTY;
GetMethod getMethod = null;
StringBuffer strtTotalURL = new StringBuffer(EMPTY);

if(strtTotalURL.indexOf("?") == -1) {
strtTotalURL.append(url).append("?").append(getUrl(params, enc));
} else {
strtTotalURL.append(url).append("&").append(getUrl(params, enc));
}
logger.debug("GET请求URL = \n" + strtTotalURL.toString());

try {
getMethod = new GetMethod(String.valueOf(strtTotalURL));
getMethod.setRequestHeader("Content-Type", "application/json;charset=" + enc);
//执行getMethod
int statusCode = client.executeMethod(getMethod);
if(statusCode == HttpStatus.SC_OK) {
response = getMethod.getResponseBodyAsString();
}else{
logger.debug("响应状态码 = " + getMethod.getStatusCode());
}
}catch(HttpException e){
logger.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
e.printStackTrace();
response = null;
}catch(IOException e){
logger.error("发生网络异常", e);
e.printStackTrace();
response = null;
}finally{
if(getMethod != null){
getMethod.releaseConnection();
getMethod = null;
}
}

return String.valueOf(response);
}

/**
* 据Map生成URL字符串
* @param map
* Map
* @param valueEnc
* URL编码
* @return
* URL
*/
private static String getUrl(Map<String, String> map, String valueEnc) {

if (null == map || map.keySet().size() == 0) {
return (EMPTY);
}
StringBuffer url = new StringBuffer();
Set<String> keys = map.keySet();
for (Iterator<String> it = keys.iterator(); it.hasNext();) {
String key = it.next();
if (map.containsKey(key)) {
String val = map.get(key);
String str = val != null ? val : EMPTY;
try {
str = URLEncoder.encode(str, valueEnc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);
}
}
String strURL = EMPTY;
strURL = url.toString();
if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {
strURL = strURL.substring(0, strURL.length() - 1);
}

return (strURL);
}

/**
* Hutool GET方式提交数据
* @param url
* 待请求的URL
* @param params
* 要提交的数据
* @return
* 响应结果
* @throws IOException
* IO异常
*/
public static String doGet(String url, Map<String, String> params){
Map<String, Object> method = new HashMap<>();
String response = "";
if (params != null) {
//HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
//p.setParameter(entry.getKey(), entry.getValue());
method.put(entry.getKey(), String.valueOf(entry.getValue()));
}
}
try {
// response = HttpUtil.get(url, method,10000);
response = HttpRequest.get(url).header(cn.hutool.http.Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
.form(method)//表单内容
.setConnectionTimeout(10000)//超时,毫秒
.setReadTimeout(600000)
.execute().body();

}catch(Exception e){
logger.error("发生异常", e);
e.printStackTrace();
response = null;
}
return String.valueOf(response);
}

/**
* Hutool POST方式提交数据
* @param url
* 待请求的URL
* @param params
* 要提交的数据
* @return
* 响应结果
* @throws IOException
* IO异常
*/
public static String doPost(String url, Map<String, String> params){
Map<String, Object> method = new HashMap<>();
String response = "";
if (params != null) {
//HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
//p.setParameter(entry.getKey(), entry.getValue());
method.put(entry.getKey(), String.valueOf(entry.getValue()));
}
}
try {
// response = HttpUtil.post(url, method,10000);
response = HttpRequest.post(url).header(cn.hutool.http.Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
.form(method)//表单内容
.setConnectionTimeout(10000)//超时,毫秒
.setReadTimeout(600000)
.execute().body();

}catch(Exception e){
logger.error("发生异常", e);
e.printStackTrace();
response = null;
}finally {
return String.valueOf(response);
}
}

}
 
posted @ 2022-06-23 14:54  全琪俊  阅读(4605)  评论(0编辑  收藏  举报