1.引入相关依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
2.http客户端参数类
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "operation.httpclient")
@Getter
@Setter
public class HttpClientProperties {
private String maxTotal;
private String maxPerRoute;
private String timeOut;
private String needretry;
}
3.工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.*;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
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;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpTookit {
private static Logger logger = LoggerFactory.getLogger(HttpTookit.class);
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "UTF-8";
private static int timeout = 360000;
private static boolean needRetry = false;
private static HttpClientProperties properties = new HttpClientProperties();
public HttpTookit() {
}
public static boolean initParms() {
return true;
}
public static String doGet(String url, Map<String, String> params) {
return doGet(url, params, null, "UTF-8");
}
public static String doPost(String url, Map<String, String> params) {
return doPost(url, params, null, "UTF-8");
}
public static String doDelete(String url, Map<String, String> params) {
return doDelete(url, params, null, "UTF-8");
}
public static String doPut(String url, Map<String, String> params) {
return doPut(url, params, null, "UTF-8");
}
public static String doGet(String url, Map<String, String> params, Map<String, String> headers) {
return doGet(url, params, headers, "UTF-8");
}
public static String doPost(String url, Map<String, String> params, Map<String, String> headers) {
return doPost(url, params, headers, "UTF-8");
}
public static String doDelete(String url, Map<String, String> params, Map<String, String> headers) {
return doDelete(url, params, headers, "UTF-8");
}
public static String doPostWithJson(String url, String json, Map<String, String> headers) {
return doPostWithJson(url, json, headers, "UTF-8");
}
public static String doPut(String url, Map<String, String> params, Map<String, String> headers) {
return doPut(url, params, headers, "UTF-8");
}
public static String doPostFile(String url, Map<String, String> params, Map<String, String> headers, String filepath) {
return doPostFile(url, params, headers, filepath, "UTF-8");
}
public static String doGet(String url, Map<String, String> params, Map<String, String> headers, String charset) {
if (StringUtils.isBlank(url)) {
return null;
} else {
try {
Iterator i$;
Entry entry;
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList(params.size());
i$ = params.entrySet().iterator();
while (i$.hasNext()) {
entry = (Entry) i$.next();
String value = (String) entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair((String) entry.getKey(), value));
}
}
url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
if (headers != null && !headers.isEmpty()) {
i$ = headers.entrySet().iterator();
while (i$.hasNext()) {
entry = (Entry) i$.next();
httpGet.addHeader((String) entry.getKey(), (String) entry.getValue());
}
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpGet.setConfig(requestConfig);
entry = null;
CloseableHttpResponse response;
try {
response = httpClient.execute(httpGet);
} catch (HttpHostConnectException | ConnectTimeoutException var10) {
logger.error("connect timeout, will reconnect", var10);
response = httpClient.execute(httpGet);
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
} else {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
httpGet.releaseConnection();
return result;
}
} catch (Exception var11) {
logger.error("Exception e " + var11.getMessage(), var11);
return null;
}
}
}
public static String doPost(String url, Map<String, String> params, Map<String, String> headers, String charset) {
if (StringUtils.isBlank(url)) {
return null;
} else {
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList(params.size());
Iterator i$ = params.entrySet().iterator();
while (i$.hasNext()) {
Entry<String, String> entry = (Entry) i$.next();
String value = entry.getValue();
if (StringUtils.isNotBlank(value)) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
HttpPost httpPost = new HttpPost(url);
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
}
if (headers != null && !headers.isEmpty()) {
Iterator i$ = headers.entrySet().iterator();
while (i$.hasNext()) {
Entry<String, String> entry = (Entry) i$.next();
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
} else {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
httpPost.releaseConnection();
return result;
}
} catch (Exception var11) {
logger.error("Exception e " + var11.getMessage(), var11);
return null;
}
}
}
public static String doPostFile(String url, Map<String, String> params, Map<String, String> headers, String filepath, String charset) {
if (StringUtils.isBlank(url)) {
return null;
} else {
try {
FileBody bin = new FileBody(new File(filepath));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", bin);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(builder.build());
if (headers != null && !headers.isEmpty()) {
Iterator i$ = headers.entrySet().iterator();
while (i$.hasNext()) {
Entry<String, String> entry = (Entry) i$.next();
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
} else {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
httpPost.releaseConnection();
return result;
}
} catch (Exception var12) {
logger.error("Exception e " + var12.getMessage(), var12);
return null;
}
}
}
public static String doPostWithJson(String url, String json, Map<String, String> headers, String charset) {
if (StringUtils.isBlank(url)) {
return null;
} else {
try {
HttpPost httpPost = new HttpPost(url);
if (headers != null && !headers.isEmpty()) {
for (Object o : headers.entrySet()) {
Entry<String, String> entry = (Entry) o;
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
StringEntity s = new StringEntity(json, "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
httpPost.setEntity(s);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
} else {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
httpPost.releaseConnection();
return result;
}
} catch (Exception var11) {
logger.error("Exception e " + var11.getMessage(), var11);
return null;
}
}
}
public static String doDelete(String url, Map<String, String> params, Map<String, String> headers, String charset) {
if (StringUtils.isBlank(url)) {
return null;
} else {
try {
Iterator i$;
Entry entry;
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList(params.size());
i$ = params.entrySet().iterator();
while (i$.hasNext()) {
entry = (Entry) i$.next();
String value = (String) entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair((String) entry.getKey(), value));
}
}
url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpDelete httpDelete = new HttpDelete(url);
if (headers != null && !headers.isEmpty()) {
i$ = headers.entrySet().iterator();
while (i$.hasNext()) {
entry = (Entry) i$.next();
httpDelete.addHeader((String) entry.getKey(), (String) entry.getValue());
}
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpDelete);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpDelete.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
} else {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
httpDelete.releaseConnection();
return result;
}
} catch (Exception var10) {
logger.error("Exception e " + var10.getMessage(), var10);
return null;
}
}
}
public static String doPut(String url, Map<String, String> params, Map<String, String> headers, String charset) {
if (StringUtils.isBlank(url)) {
return null;
} else {
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList(params.size());
Iterator i$ = params.entrySet().iterator();
while (i$.hasNext()) {
Entry<String, String> entry = (Entry) i$.next();
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
HttpPut httpPut = new HttpPut(url);
if (pairs != null && pairs.size() > 0) {
httpPut.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
}
if (headers != null && !headers.isEmpty()) {
Iterator i$ = headers.entrySet().iterator();
while (i$.hasNext()) {
Entry<String, String> entry = (Entry) i$.next();
httpPut.addHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPut.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
} else {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
httpPut.releaseConnection();
return result;
}
} catch (Exception var10) {
logger.error("Exception e " + var10.getMessage(), var10);
return null;
}
}
}
public static void setProperties(HttpClientProperties properties) {
HttpTookit.properties = properties;
}
static {
String maxTotal = HttpTookit.properties.getMaxTotal();
String maxPerRoute = HttpTookit.properties.getMaxPerRoute();
if (maxTotal == null) {
maxTotal = "100";
}
if (maxPerRoute == null) {
maxPerRoute = "100";
}
String timeOut = HttpTookit.properties.getTimeOut();
if (timeOut != null) {
try {
timeout = Integer.valueOf(timeOut).intValue();
if (timeout > 500) {
timeout = 500;
}
timeout *= 1000;
} catch (Exception var8) {
logger.error("Exception e " + var8.getMessage(), var8);
}
}
RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(Integer.valueOf(maxTotal).intValue());
cm.setDefaultMaxPerRoute(Integer.valueOf(maxPerRoute).intValue());
String retryStr = HttpTookit.properties.getNeedretry();
if (retryStr != null) {
needRetry = Boolean.valueOf(retryStr).booleanValue();
}
if (needRetry) {
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setConnectionManager(cm).setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build();
} else {
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setConnectionManager(cm).build();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗