package com.ruoyi.utils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
/**
*
* @Description: Http工具
* @author: k
* @date: 2022年8月22日 上午9:26:54
*/
public class HttpUtil {
private static final int CONNECT_TIMEOUT=5000;
private static final int SOCKET_TIMEOUT=10000;
static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
public static String doGet(String url, Map<String, String> requestParam, Map<String, String> headerParam) {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
String param = "";
if (requestParam != null) {
StringBuffer buffer = new StringBuffer();
buffer.append("?");
requestParam.forEach((k, v) -> {
buffer.append(k + "=" + v + "&");
});
param = buffer.toString().substring(0, buffer.length() - 1);
}
// 创建Get请求
HttpGet httpGet = new HttpGet(url + param);
httpGet.setConfig(requestConfig);
if (headerParam != null) {
headerParam.forEach((k, v) -> {
httpGet.setHeader(k, v);
});
}
String result = null;
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPostJson(String url, JSONObject requestParam, Map<String, String> headerParam) {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(url);
// httpPost.setConfig(requestConfig);
StringEntity entity = new StringEntity(requestParam.toJSONString(), "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
String result = null;
// 响应模型
CloseableHttpResponse response = null;
try {
if (headerParam != null) {
headerParam.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
}
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
// System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPostXWWWFormUrlEncoded(String url, Map<String, String> requestParam, Map<String, String> headerParam) {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
//装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (requestParam != null) {
requestParam.forEach((k, v) -> {
nvps.add(new BasicNameValuePair(k, v));
});
}
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
String result = null;
// 响应模型
CloseableHttpResponse response = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
if (headerParam != null) {
headerParam.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
}
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
// System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPostFormData(String url, String fileName, Map<String, String> requestParam, Map<String, String> headerParam) {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
String result = null;
try {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 第一个文件(多个文件的话,使用同一个key就行,后端用数组或集合进行接收即可)
String filesKey = "file";
File file = new File(fileName);
multipartEntityBuilder.addBinaryBody(filesKey, file);
// 防止服务端收到的文件名乱码。 我们这里可以先将文件名URLEncode,然后服务端拿到文件名时在URLDecode。就能避免乱码问题。
// 文件名其实是放在请求头的Content-Disposition里面进行传输的,如其值为form-data; name="files"; filename="头像.jpg"
// multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
// 其它参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码)
if (requestParam != null) {
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
requestParam.forEach((k, v) -> {
multipartEntityBuilder.addTextBody(k, v, contentType);
});
}
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 主动设置编码,来防止响应乱码
result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
java 常规http请求工具类
最新推荐文章于 2025-03-04 10:43:42 发布