package com.cmcc.ac.health.pay.util.http;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpClientConnectionManager;
import org.apache.http.entity.ContentType;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
private static PoolingHttpClientConnectionManager connectionManager;
private static RequestConfig requestConfig;
private static HttpUtil newHttpUtil = new HttpUtil();
private static IdleConnectionMonitorThread ict;
private HttpUtil() {
connectionManager = new PoolingHttpClientConnectionManager();
int defaultMaxTotal = 3000;
connectionManager.setMaxTotal(defaultMaxTotal);
int defaultMaxPerRoute = 400;
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
int defaultConnectRequestTimeOut = 5 * 1000;
int defaultSocketTimeOut = 10 * 1000;
int defaultConnectTimeOut = 10 * 1000;
requestConfig = RequestConfig.custom().setSocketTimeout(defaultSocketTimeOut)
.setConnectionRequestTimeout(defaultConnectRequestTimeOut)
.setConnectTimeout(defaultConnectTimeOut).build();
ict = new IdleConnectionMonitorThread(connectionManager);
int defalutClearTime = 5000;
ict.setClearTime(defalutClearTime);
ict.start();
}
public static HttpUtil getInstance() {
return newHttpUtil;
}
public static void destroy() {
ict.shutdown();
}
public String sendPostByMap(String url, Map<String, String> map) {
return sendPostByMap(url, map, null);
}
public String sendPostByMap(String url, Map<String, String> map, String revCharset) {
List<NameValuePair> list = new ArrayList<>();
if (map != null && map.size() > 0) {
for (Entry<String, String> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
return sendByNameValuePairs(url, list, revCharset);
}
public String sendByJson(String url, String json) {
return sendHttpPost(url, new StringEntity(json, ContentType.create("application/json",
Consts.UTF_8)), "utf-8");
}
public String sendByJson(String url, String json, String charset) {
return sendHttpPost(url, new StringEntity(json, ContentType.create("application/json",
charset)), charset);
}
public String sendPostByString(String url, String str, ContentType contentType, String charType) {
return sendHttpPost(url, new StringEntity(str, contentType), charType);
}
public String sendByNameValuePairs(String url, List<NameValuePair> nvps) {
return sendByNameValuePairs(url, nvps, null);
}
public String sendByNameValuePairs(String url, List<NameValuePair> nvps, String revCharset) {
return sendHttpPost(url, new UrlEncodedFormEntity(nvps, Consts.UTF_8), revCharset);
}
public String sendByXmlPost(String url, String xml) {
return sendHttpPost(url, new StringEntity(xml, ContentType.create("application/xml", "GBK")), "GBK");
}
public String sendByIcbcXmlPost(String url, String xml) {
return sendHttpPost(url, new StringEntity(xml, ContentType.create("INFOSEC_SIGN/1.0", "ISO8859-1")), "GBK");
}
private String sendHttpPost(String url, HttpEntity entity, String revCharset) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setEntity(entity);
StringBuffer result = new StringBuffer();
BufferedReader buffer = null;
InputStreamReader isr = null;
String line;
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
InputStream input = response.getEntity().getContent();
if (revCharset == null) {
isr = new InputStreamReader(input);
} else {
isr = new InputStreamReader(input, revCharset);
}
buffer = new BufferedReader(isr, 10 * 1024);
result = new StringBuffer();
while ((line = buffer.readLine()) != null) {
result.append(line);
result.append(System.getProperty("line.separator"));
}
if (result.lastIndexOf(System.getProperty("line.separator")) != -1) {
result.delete(result.lastIndexOf(System.getProperty("line.separator")),
result.length());
}
} else {
logger.error("Http请求返回码错误:" + code);
}
} catch (ClientProtocolException e) {
logger.error("Http请求错误:", e);
} catch (IOException e) {
logger.error("IO错误:", e);
} finally {
try {
if (response != null) {
response.close();
}
if (buffer != null) {
buffer.close();
}
if (isr != null) {
isr.close();
}
} catch (IOException e) {
logger.error("IO错误:", e);
}
}
return result.toString();
}
public String sendHttpGet(String url) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
StringBuffer result = new StringBuffer();
BufferedReader buffer = null;
InputStreamReader isr = null;
String line;
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
InputStream input = response.getEntity().getContent();
isr = new InputStreamReader(input);
buffer = new BufferedReader(isr, 10 * 1024);
result = new StringBuffer();
while ((line = buffer.readLine()) != null) {
result.append(line);
result.append(System.getProperty("line.separator"));
}
if (result.lastIndexOf(System.getProperty("line.separator")) != -1) {
result.delete(result.lastIndexOf(System.getProperty("line.separator")),
result.length());
}
} else {
logger.error("Http请求返回码错误:" + code);
}
} catch (ClientProtocolException e) {
logger.error("Http请求错误:", e);
} catch (IOException e) {
logger.error("IO错误:", e);
} finally {
try {
if (response != null) {
response.close();
}
if (buffer != null) {
buffer.close();
}
if (isr != null) {
isr.close();
}
} catch (IOException e) {
logger.error("IO错误:", e);
}
}
return result.toString();
}
private static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
private int clearTime = 5000;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
public void setClearTime(int clearTime) {
this.clearTime = clearTime;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(clearTime);
connMgr.closeExpiredConnections();
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
logger.error("异常:", ex);
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!