普通Java程序想要发送Get、Post等请求可以采用HttpClient实现,下面给出HttpClient使用方法,并已经封装成方法,直接拿去用即可
在maven中导入依赖:
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpmimeartifactId>
<version>4.5.13version>
dependency>
记得在类中写上一个静态变量:private static HttpClient client = HttpClients.createDefault();
/**
* 发送HttpGet请求
* @param url 请求的url
* @param params get请求携带的参数
* @param headers 请求头需要额外携带的参数
* @return Sting格式的响应结果
*/
public static String Get(String url, HashMap<String, String> params, HashMap<String, String> headers) {
HttpGet httpGet = new HttpGet();
// 设置请求头
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpGet.addHeader("Connection", "keep-alive");
httpGet.addHeader("Content-Type", "application/json; charset=utf-8");
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36");
if (headers != null && headers.size() > 0) {
headers.forEach(httpGet::addHeader);
}
// 设置参数
if (params != null && params.size() > 0) {
StringBuilder newUrl = new StringBuilder(url + "?");
params.forEach((k, v) -> newUrl.append(k).append("=").append(v).append("&"));
httpGet.setURI(URI.create(newUrl.toString()));
}
String response;
try {
HttpResponse execute = client.execute(httpGet);
// 获取响应实体
HttpEntity responseEntity = execute.getEntity();
response = responseEntity != null ? EntityUtils.toString(responseEntity, "UTF-8") : "响应结果为null";
} catch (IOException e) {
throw new RuntimeException(e);
}
return response;
}
记得在类中写上一个静态变量:private static HttpClient client = HttpClients.createDefault();
/**
* 发送HttpPost请求
* @param url 请求的url
* @param payloads post请求携带的请求体
* @param headers 请求头需要额外携带的参数
* @return Sting格式的响应结果
*/
public static String Post(String url, HashMap<String, String> payloads, HashMap<String, String> headers) {
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.addHeader("Connection", "keep-alive");
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36");
if (headers != null && headers.size() > 0) {
headers.forEach(httpPost::addHeader);
}
// 构建请求体参数
if (payloads != null && payloads.size() > 0) {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
payloads.forEach((k, v) -> {
if (k.equals("Boundary")) {
entityBuilder.setBoundary(v);
} else {
entityBuilder.addTextBody(k, v);
}
});
httpPost.setEntity(entityBuilder.build());
}
String response;
try {
HttpResponse execute = client.execute(httpPost);
// 获取响应实体
HttpEntity responseEntity = execute.getEntity();
response = responseEntity != null ? EntityUtils.toString(responseEntity, "UTF-8") : "响应结果为null";
} catch (IOException e) {
throw new RuntimeException(e);
}
return response;
}