document.write("");

post 请求工具类

 

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
 
@Slf4j
public class PostRequestUtils {
 
    public PostRequestUtils() {
    }
 
    /**
     * 发送POST请求并返回结果
     *
     * @param proxyAddress 代理服务器地址
     * @param proxyPort    代理服务器端口
     * @param postUrl      请求URL
     * @param data         请求数据
     * @return 返回结果
     * @throws Exception 抛出异常
     */
    public String sendMsg(String proxyAddress, String proxyPort, String postUrl, String data) throws Exception {
        PrintWriter out = null;
        BufferedReader reader = null;
        String result = null;
        String returnCode = null;
 
        try {
            if (data != null && !data.isEmpty()) {
                // 创建连接
                URL url = new URL(postUrl);
                // 忽略证书校验
                ignoreSsl(postUrl);
                // 设置代理
                HttpURLConnection connection = createConnection(url, proxyAddress, proxyPort);
 
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(false);
                connection.setRequestProperty("Charset", "UTF-8");
                connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                connection.setRequestProperty("Connection", "Keep-Alive");
 
                connection.connect();
 
                // POST请求
                out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8), true);
                out.write(data);
                out.flush();
                out.close();
 
                // 从HTTP取得返回结果
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                returnCode = parseReturnMsg(sb.toString());
                log.info("接口返回:" + returnCode);
                reader.close();
                // 断开连接
                connection.disconnect();
            }
        } catch (IOException e) {
            log.error("发生异常: {}", e.getMessage(), e);
        } finally {
            closeQuietly(out);
            closeQuietly(reader);
        }
        return returnCode;
    }
 
    /**
     * 解析返回的消息
     *
     * @param jsonData JSON格式的返回数据
     * @return 解析后的结果
     */
    public String parseReturnMsg(String jsonData) {
        try {
            log.info("接收到的JSON数据: {}", jsonData);
            JSONObject jsonObject = JSONObject.parseObject(jsonData);
            JSONObject result = jsonObject.getJSONObject("result");
            return result.getString("code");
        } catch (Exception e) {
            log.error("解析JSON数据时发生异常: {}", e.getMessage(), e);
        }
        return null;
    }
 
    /**
     * 读取输入流并返回字节数组
     *
     * @param inStream 输入流
     * @return 字节数组
     * @throws Exception 抛出异常
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            return outStream.toByteArray();
        } finally {
            inStream.close();
        }
    }
 
    /**
     * 忽略SSL证书校验
     *
     * @param postUrl 请求URL
     * @throws Exception 抛出异常
     */
    public static void ignoreSsl(String postUrl) throws Exception {
        HostnameVerifier hv = (url, session) -> {
            log.warn("警告: URL Host: {} vs. {}", url, session.getPeerHost());
            return true;
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
 
    /**
     * 信任所有HTTPS证书
     *
     * @throws Exception 抛出异常
     */
    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{new miTM()};
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
 
    /**
     * 自定义信任管理器
     */
    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
 
        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }
 
        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }
 
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
 
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
 
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 请求URL
     * @return 返回结果
     */
    public static String get(String url) {
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 创建代理服务器
            InetSocketAddress addr = new InetSocketAddress("10.12.129.9", 8080);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // HTTP代理
 
            // 不使用代理
            URLConnection connection = realUrl.openConnection();
            // 使用代理
            // URLConnection connection = realUrl.openConnection(proxy);
 
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;");
 
            // 建立实际的连接
            connection.connect();
 
            // 读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            log.error("发生异常: {}", e.getMessage(), e);
        } finally {
            closeQuietly(in);
        }
        return "";
    }
 
    /**
     * 关闭PrintWriter,忽略关闭时的异常
     *
     * @param out PrintWriter对象
     */
    private static void closeQuietly(PrintWriter out) {
        if (out != null) {
            try {
                out.close();
            } catch (Exception ignored) {
            }
        }
    }
 
    /**
     * 关闭BufferedReader,忽略关闭时的异常
     *
     * @param reader BufferedReader对象
     */
    private static void closeQuietly(BufferedReader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignored) {
            }
        }
    }
 
    /**
     * 创建HTTP连接
     *
     * @param url          请求URL
     * @param proxyAddress 代理服务器地址
     * @param proxyPort    代理服务器端口
     * @return HttpURLConnection对象
     * @throws IOException 抛出IO异常
     */
    private static HttpURLConnection createConnection(URL url, String proxyAddress, String proxyPort) throws IOException {
        if (proxyPort == null || Integer.parseInt(proxyPort) == 0) {
            return (HttpURLConnection) url.openConnection();
        } else {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, Integer.parseInt(proxyPort)));
            return (HttpURLConnection) url.openConnection(proxy);
        }
    }
}

  

posted @   人间春风意  阅读(82)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示

距今时间:
1025天8.00 小时 52.61 分钟

当前新增阅读数:140327