HttpUtils.java
2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package cn.com.glsx.entmicro.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
/**
* HTTP工具类
* 用于发送HTTP请求
*
* @author system
* @date 2026-03-31
*/
@Slf4j
public class HttpUtils {
/**
* 发送POST请求
* @param url 请求地址
* @param params 请求参数
* @return 响应结果
*/
public static String post(String url, String params) {
try {
javax.net.ssl.SSLContext ctx = SSLContexts.custom()
.useProtocol("TLSv1.2").build();
// 定义HttpClient
HttpClient client = HttpClientBuilder.create().setSslcontext(ctx)
.build();
BufferedReader in = null;
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));
// 设置参数
request.setEntity(new StringEntity(params, HTTP.UTF_8));
request.addHeader("Content-Type", "application/json;charset=utf-8");
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if (code == 200) { // 请求成功
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
} else { //
log.warn("HTTP请求失败,状态码:{}", code);
return null;
}
} catch (Exception e) {
log.error("HTTP请求异常", e);
return null;
}
}
/**
* 发送POST请求(JSON格式)
* @param url 请求地址
* @param jsonObject JSON对象
* @return 响应结果
*/
public static String postJson(String url, JSONObject jsonObject) {
return post(url, jsonObject.toJSONString());
}
}