dengzedong
2025-01-10 ed5f75dce72b05d095c52228a0b46d312cebaa4c
提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.common.util.http;
H 2
3 import cn.hutool.core.codec.Base64;
4 import cn.hutool.core.map.TableMap;
5 import cn.hutool.core.net.url.UrlBuilder;
6 import cn.hutool.core.util.ReflectUtil;
7 import cn.hutool.core.util.StrUtil;
d7fd46 8 import org.springframework.util.CollectionUtils;
e7c126 9 import org.springframework.util.StringUtils;
H 10 import org.springframework.web.util.UriComponents;
11 import org.springframework.web.util.UriComponentsBuilder;
12
13 import javax.servlet.http.HttpServletRequest;
d7fd46 14 import java.io.BufferedReader;
H 15 import java.io.IOException;
16 import java.io.InputStreamReader;
17 import java.io.PrintWriter;
e7c126 18 import java.net.URI;
d7fd46 19 import java.net.URL;
H 20 import java.net.URLConnection;
e7c126 21 import java.nio.charset.Charset;
d7fd46 22 import java.util.List;
e7c126 23 import java.util.Map;
H 24
25 /**
26  * HTTP 工具类
27  *
28  * @author iailab
29  */
30 public class HttpUtils {
31
32     @SuppressWarnings("unchecked")
33     public static String replaceUrlQuery(String url, String key, String value) {
34         UrlBuilder builder = UrlBuilder.of(url, Charset.defaultCharset());
35         // 先移除
36         TableMap<CharSequence, CharSequence> query = (TableMap<CharSequence, CharSequence>)
37                 ReflectUtil.getFieldValue(builder.getQuery(), "query");
38         query.remove(key);
39         // 后添加
40         builder.addQuery(key, value);
41         return builder.build();
42     }
43
44     private String append(String base, Map<String, ?> query, boolean fragment) {
45         return append(base, query, null, fragment);
46     }
47
48     /**
49      * 拼接 URL
50      *
51      * copy from Spring Security OAuth2 的 AuthorizationEndpoint 类的 append 方法
52      *
53      * @param base 基础 URL
54      * @param query 查询参数
55      * @param keys query 的 key,对应的原本的 key 的映射。例如说 query 里有个 key 是 xx,实际它的 key 是 extra_xx,则通过 keys 里添加这个映射
56      * @param fragment URL 的 fragment,即拼接到 # 中
57      * @return 拼接后的 URL
58      */
59     public static String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {
60         UriComponentsBuilder template = UriComponentsBuilder.newInstance();
61         UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
62         URI redirectUri;
63         try {
64             // assume it's encoded to start with (if it came in over the wire)
65             redirectUri = builder.build(true).toUri();
66         } catch (Exception e) {
67             // ... but allow client registrations to contain hard-coded non-encoded values
68             redirectUri = builder.build().toUri();
69             builder = UriComponentsBuilder.fromUri(redirectUri);
70         }
71         template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost())
72                 .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());
73
74         if (fragment) {
75             StringBuilder values = new StringBuilder();
76             if (redirectUri.getFragment() != null) {
77                 String append = redirectUri.getFragment();
78                 values.append(append);
79             }
80             for (String key : query.keySet()) {
81                 if (values.length() > 0) {
82                     values.append("&");
83                 }
84                 String name = key;
85                 if (keys != null && keys.containsKey(key)) {
86                     name = keys.get(key);
87                 }
88                 values.append(name).append("={").append(key).append("}");
89             }
90             if (values.length() > 0) {
91                 template.fragment(values.toString());
92             }
93             UriComponents encoded = template.build().expand(query).encode();
94             builder.fragment(encoded.getFragment());
95         } else {
96             for (String key : query.keySet()) {
97                 String name = key;
98                 if (keys != null && keys.containsKey(key)) {
99                     name = keys.get(key);
100                 }
101                 template.queryParam(name, "{" + key + "}");
102             }
103             template.fragment(redirectUri.getFragment());
104             UriComponents encoded = template.build().expand(query).encode();
105             builder.query(encoded.getQuery());
106         }
107         return builder.build().toUriString();
108     }
109
110     public static String[] obtainBasicAuthorization(HttpServletRequest request) {
111         String clientId;
112         String clientSecret;
113         // 先从 Header 中获取
114         String authorization = request.getHeader("Authorization");
115         authorization = StrUtil.subAfter(authorization, "Basic ", true);
116         if (StringUtils.hasText(authorization)) {
117             authorization = Base64.decodeStr(authorization);
118             clientId = StrUtil.subBefore(authorization, ":", false);
119             clientSecret = StrUtil.subAfter(authorization, ":", false);
120         // 再从 Param 中获取
121         } else {
122             clientId = request.getParameter("client_id");
123             clientSecret = request.getParameter("client_secret");
124         }
125
126         // 如果两者非空,则返回
127         if (StrUtil.isNotEmpty(clientId) && StrUtil.isNotEmpty(clientSecret)) {
128             return new String[]{clientId, clientSecret};
129         }
130         return null;
131     }
132
d7fd46 133     /**
H 134      * 向指定URL发送GET方法的请求
135      *
136      * @param url   发送请求的URL
137      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
138      * @return URL 所代表远程资源的响应结果
139      */
140     public static String sendGet(String url, String param) {
141         String result = "";
142         BufferedReader in = null;
143         try {
144             String urlNameString = url + "?" + param;
145             URL realUrl = new URL(urlNameString);
146             // 打开和URL之间的连接
147             URLConnection connection = realUrl.openConnection();
148             // 设置通用的请求属性
149             connection.setRequestProperty("accept", "*/*");
150             connection.setRequestProperty("connection", "Keep-Alive");
151             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
152
153             // 建立实际的连接
154             connection.connect();
155             // 获取所有响应头字段
156             Map<String, List<String>> map = connection.getHeaderFields();
157             // 遍历所有的响应头字段
158             for (String key : map.keySet()) {
159                 System.out.println(key + "--->" + map.get(key));
160             }
161             // 定义 BufferedReader输入流来读取URL的响应
162             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
163             String line;
164             while ((line = in.readLine()) != null) {
165                 result += line;
166             }
167         } catch (Exception e) {
168             System.out.println("发送GET请求出现异常!" + e);
169             e.printStackTrace();
170         }
171         // 使用finally块来关闭输入流
172         finally {
173             try {
174                 if (in != null) {
175                     in.close();
176                 }
177             } catch (Exception e2) {
178                 e2.printStackTrace();
179             }
180         }
181         return result;
182     }
183
184     public static String sendGet(String url, Map<String, String> params, String authorization) {
185         String result = "";
186         BufferedReader in = null;
187         try {
188             StringBuilder sb = new StringBuilder();
189             sb.append(url);
190             if (!CollectionUtils.isEmpty(params)) {
191                 sb.append("?");
192                 params.forEach((k, v) -> {
193                     sb.append(k + "=" + v + "&");
194                 });
195                 sb.append("t=" + System.currentTimeMillis());
196             }
197             String urlNameString = sb.toString();
198             URL realUrl = new URL(urlNameString);
199             // 打开和URL之间的连接
200             URLConnection connection = realUrl.openConnection();
201             // 设置通用的请求属性
202             connection.setRequestProperty("Authorization", authorization);
203             connection.setRequestProperty("accept", "*/*");
204             connection.setRequestProperty("connection", "Keep-Alive");
205             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
206
207             // 建立实际的连接
208             connection.connect();
209             // 获取所有响应头字段
210             Map<String, List<String>> map = connection.getHeaderFields();
211             // 遍历所有的响应头字段
212             for (String key : map.keySet()) {
213                 System.out.println(key + "--->" + map.get(key));
214             }
215             // 定义 BufferedReader输入流来读取URL的响应
216             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
217             String line;
218             while ((line = in.readLine()) != null) {
219                 result += line;
220             }
221         } catch (Exception e) {
222             System.out.println("发送GET请求出现异常!" + e);
223             e.printStackTrace();
224         }
225         // 使用finally块来关闭输入流
226         finally {
227             try {
228                 if (in != null) {
229                     in.close();
230                 }
231             } catch (Exception e2) {
232                 e2.printStackTrace();
233             }
234         }
235         return result;
236     }
237
238     /**
239      * 向指定 URL 发送POST方法的请求
240      *
241      * @param url
242      * @param json
243      * @return
244      */
245     public static String sendPost(String url, String json) {
246         PrintWriter out = null;
247         BufferedReader in = null;
248         String result = "";
249         try {
250             URL realUrl = new URL(url);
251             // 打开和URL之间的连接
252             URLConnection conn = realUrl.openConnection();
253             // 设置通用的请求属性
254             conn.setRequestProperty("content-type", "application/json");
255             conn.setRequestProperty("accept", "*/*");
256             conn.setRequestProperty("connection", "Keep-Alive");
257             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
258
259             // 发送POST请求必须设置如下两行
260             conn.setDoOutput(true);
261             conn.setDoInput(true);
262             // 获取URLConnection对象对应的输出流
263             out = new PrintWriter(conn.getOutputStream());
264             // 发送请求参数
265             out.print(json);
266             // flush输出流的缓冲
267             out.flush();
268             // 定义BufferedReader输入流来读取URL的响应
269             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
270             String line;
271             while ((line = in.readLine()) != null) {
272                 result += line;
273             }
274         } catch (Exception e) {
275             System.out.println("发送 POST 请求出现异常!" + e);
276             e.printStackTrace();
277         }
278         //使用finally块来关闭输出流、输入流
279         finally {
280             try {
281                 if (out != null) {
282                     out.close();
283                 }
284                 if (in != null) {
285                     in.close();
286                 }
287             } catch (IOException ex) {
288                 ex.printStackTrace();
289             }
290         }
291         return result;
292     }
293
294     /**
295      * 向指定 URL 发送POST方法的请求
296      *
297      * @param url
298      * @param json
299      * @param authorization
300      * @return
301      */
302     public static String sendPost(String url, String json, String authorization) {
303         PrintWriter out = null;
304         BufferedReader in = null;
305         String result = "";
306         try {
307             URL realUrl = new URL(url);
308             // 打开和URL之间的连接
309             URLConnection conn = realUrl.openConnection();
310             // 设置通用的请求属性
311             conn.setRequestProperty("Authorization", authorization);
312             conn.setRequestProperty("accept", "*/*");
313             conn.setRequestProperty("connection", "Keep-Alive");
314             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
315
316             // 发送POST请求必须设置如下两行
317             conn.setDoOutput(true);
318             conn.setDoInput(true);
319             // 获取URLConnection对象对应的输出流
320             out = new PrintWriter(conn.getOutputStream());
321             // 发送请求参数
322             out.print(json);
323             // flush输出流的缓冲
324             out.flush();
325             // 定义BufferedReader输入流来读取URL的响应
326             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
327             String line;
328             while ((line = in.readLine()) != null) {
329                 result += line;
330             }
331         } catch (Exception e) {
332             System.out.println("发送 POST 请求出现异常!" + e);
333             e.printStackTrace();
334         }
335         //使用finally块来关闭输出流、输入流
336         finally {
337             try {
338                 if (out != null) {
339                     out.close();
340                 }
341                 if (in != null) {
342                     in.close();
343                 }
344             } catch (IOException ex) {
345                 ex.printStackTrace();
346             }
347         }
348         return result;
349     }
350
e7c126 351
H 352 }