houzhongjian
2024-11-14 08b6a55a3a111aaee9842999b85afa60b6d61dc3
提交 | 用户 | 时间
a6de49 1 package com.iailab.module.data.common.utils;
H 2
149dd0 3 import com.iailab.framework.tenant.core.context.TenantContextHolder;
ce910c 4 import org.apache.http.HttpEntity;
H 5 import org.apache.http.HttpResponse;
6 import org.apache.http.client.methods.HttpPost;
7 import org.apache.http.entity.StringEntity;
8 import org.apache.http.util.EntityUtils;
a6de49 9 import org.springframework.util.CollectionUtils;
H 10
11 import java.io.BufferedReader;
12 import java.io.IOException;
13 import java.io.InputStreamReader;
14 import java.io.PrintWriter;
15 import java.net.URL;
16 import java.net.URLConnection;
17 import java.util.List;
18 import java.util.Map;
19
20 /**
21  * @author PanZhibao
22  * @date 2021年06月03日 15:31
23  */
24 public class HttpRequest {
25     /**
26      * 向指定URL发送GET方法的请求
27      *
28      * @param url   发送请求的URL
29      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
30      * @return URL 所代表远程资源的响应结果
31      */
32     public static String sendGet(String url, String param) {
33         String result = "";
34         BufferedReader in = null;
35         try {
36             String urlNameString = url + "?" + param;
37             URL realUrl = new URL(urlNameString);
38             // 打开和URL之间的连接
39             URLConnection connection = realUrl.openConnection();
40             // 设置通用的请求属性
41             connection.setRequestProperty("accept", "*/*");
42             connection.setRequestProperty("connection", "Keep-Alive");
43             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
44
45             // 建立实际的连接
46             connection.connect();
47             // 获取所有响应头字段
48             Map<String, List<String>> map = connection.getHeaderFields();
49             // 遍历所有的响应头字段
50             for (String key : map.keySet()) {
51                 System.out.println(key + "--->" + map.get(key));
52             }
53             // 定义 BufferedReader输入流来读取URL的响应
54             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
55             String line;
56             while ((line = in.readLine()) != null) {
57                 result += line;
58             }
59         } catch (Exception e) {
60             System.out.println("发送GET请求出现异常!" + e);
61             e.printStackTrace();
62         }
63         // 使用finally块来关闭输入流
64         finally {
65             try {
66                 if (in != null) {
67                     in.close();
68                 }
69             } catch (Exception e2) {
70                 e2.printStackTrace();
71             }
72         }
73         return result;
74     }
75
76     public static String sendGet(String url, Map<String, String> params, String authorization) {
77         String result = "";
78         BufferedReader in = null;
79         try {
80             StringBuilder sb = new StringBuilder();
81             sb.append(url);
82             if (!CollectionUtils.isEmpty(params)) {
83                 sb.append("?");
84                 params.forEach((k, v) -> {
85                     sb.append(k + "=" + v + "&");
86                 });
87                 sb.append("t=" + System.currentTimeMillis());
88             }
89             String urlNameString = sb.toString();
90             URL realUrl = new URL(urlNameString);
91             // 打开和URL之间的连接
92             URLConnection connection = realUrl.openConnection();
93             // 设置通用的请求属性
94             connection.setRequestProperty("Authorization", authorization);
95             connection.setRequestProperty("accept", "*/*");
96             connection.setRequestProperty("connection", "Keep-Alive");
97             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
98
99             // 建立实际的连接
100             connection.connect();
101             // 获取所有响应头字段
102             Map<String, List<String>> map = connection.getHeaderFields();
103             // 遍历所有的响应头字段
104             for (String key : map.keySet()) {
105                 System.out.println(key + "--->" + map.get(key));
106             }
107             // 定义 BufferedReader输入流来读取URL的响应
108             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
109             String line;
110             while ((line = in.readLine()) != null) {
111                 result += line;
112             }
113         } catch (Exception e) {
114             System.out.println("发送GET请求出现异常!" + e);
115             e.printStackTrace();
116         }
117         // 使用finally块来关闭输入流
118         finally {
119             try {
120                 if (in != null) {
121                     in.close();
122                 }
123             } catch (Exception e2) {
124                 e2.printStackTrace();
125             }
126         }
127         return result;
128     }
129
130     /**
131      * 向指定 URL 发送POST方法的请求
132      *
133      * @param url
134      * @param json
135      * @return
136      */
137     public static String sendPost(String url, String json) {
138         PrintWriter out = null;
139         BufferedReader in = null;
140         String result = "";
141         try {
142             URL realUrl = new URL(url);
143             // 打开和URL之间的连接
144             URLConnection conn = realUrl.openConnection();
145             // 设置通用的请求属性
d41f14 146             conn.setRequestProperty("content-type", "application/json");
a6de49 147             conn.setRequestProperty("accept", "*/*");
H 148             conn.setRequestProperty("connection", "Keep-Alive");
149             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
150
151             // 发送POST请求必须设置如下两行
152             conn.setDoOutput(true);
153             conn.setDoInput(true);
154             // 获取URLConnection对象对应的输出流
155             out = new PrintWriter(conn.getOutputStream());
156             // 发送请求参数
157             out.print(json);
158             // flush输出流的缓冲
159             out.flush();
160             // 定义BufferedReader输入流来读取URL的响应
161             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
162             String line;
163             while ((line = in.readLine()) != null) {
164                 result += line;
165             }
166         } catch (Exception e) {
167             System.out.println("发送 POST 请求出现异常!" + e);
168             e.printStackTrace();
169         }
170         //使用finally块来关闭输出流、输入流
171         finally {
172             try {
173                 if (out != null) {
174                     out.close();
175                 }
176                 if (in != null) {
177                     in.close();
178                 }
179             } catch (IOException ex) {
180                 ex.printStackTrace();
181             }
182         }
183         return result;
184     }
185
186     /**
187      * 向指定 URL 发送POST方法的请求
188      *
189      * @param url
190      * @param json
191      * @param authorization
192      * @return
193      */
194     public static String sendPost(String url, String json, String authorization) {
195         PrintWriter out = null;
196         BufferedReader in = null;
197         String result = "";
198         try {
199             URL realUrl = new URL(url);
200             // 打开和URL之间的连接
201             URLConnection conn = realUrl.openConnection();
202             // 设置通用的请求属性
203             conn.setRequestProperty("Authorization", authorization);
204             conn.setRequestProperty("accept", "*/*");
205             conn.setRequestProperty("connection", "Keep-Alive");
206             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
207
208             // 发送POST请求必须设置如下两行
209             conn.setDoOutput(true);
210             conn.setDoInput(true);
211             // 获取URLConnection对象对应的输出流
212             out = new PrintWriter(conn.getOutputStream());
213             // 发送请求参数
214             out.print(json);
215             // flush输出流的缓冲
216             out.flush();
217             // 定义BufferedReader输入流来读取URL的响应
218             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
219             String line;
220             while ((line = in.readLine()) != null) {
221                 result += line;
222             }
223         } catch (Exception e) {
224             System.out.println("发送 POST 请求出现异常!" + e);
225             e.printStackTrace();
226         }
227         //使用finally块来关闭输出流、输入流
228         finally {
229             try {
230                 if (out != null) {
231                     out.close();
232                 }
233                 if (in != null) {
234                     in.close();
235                 }
236             } catch (IOException ex) {
237                 ex.printStackTrace();
238             }
239         }
240         return result;
241     }
ce910c 242
H 243     /**
244      *
245      * @param url
246      * @param json
247      * @param charset
248      * @param token
249      * @return
250      */
251     public static String doPost(String url, String json, String charset, String token) {
08b6a5 252         Long tenantId = TenantContextHolder.getTenantId();
ce910c 253         org.apache.http.client.HttpClient httpClient = null;
H 254         HttpPost httpPost = null;
255         String result = null;
256         try {
257             httpClient = new SSLClient();
258             httpPost = new HttpPost(url);
259             //设置参数
260             httpPost.addHeader("Accept", "application/json");
261             httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
262             httpPost.addHeader("token", token);
08b6a5 263             httpPost.addHeader("Tenant-Id", String.valueOf(tenantId));
ce910c 264             StringEntity stringEntity = new StringEntity(json);
H 265             stringEntity.setContentEncoding("UTF-8");
266             stringEntity.setContentType("application/json");
267             httpPost.setEntity(stringEntity);
268             HttpResponse response = httpClient.execute(httpPost);
269             if (response != null) {
270                 HttpEntity resEntity = response.getEntity();
271                 if (resEntity != null) {
272                     result = EntityUtils.toString(resEntity, charset);
273                 }
274             }
275         } catch (Exception ex) {
276             ex.printStackTrace();
277         }
278         return result;
279     }
a6de49 280 }