E1ED922C1E9526DD63272D7EC5C6CB77
2021-01-20 a1dba41efa841aef8fb9f2bf2a179095ef77a9cd
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import net.sf.json.JSONException;
4 import net.sf.json.JSONObject;
5 import org.apache.commons.io.IOUtils;
a1dba4 6 import org.bouncycastle.util.encoders.UTF8;
5c5945 7 import org.springframework.web.multipart.MultipartFile;
E 8
9 import javax.activation.MimetypesFileTypeMap;
8bc3c9 10 import javax.servlet.ServletInputStream;
C 11 import javax.servlet.http.HttpServletRequest;
5c5945 12 import java.io.*;
E 13 import java.net.HttpURLConnection;
14 import java.net.URL;
a1dba4 15 import java.nio.charset.Charset;
E 16 import java.nio.charset.CharsetEncoder;
5c5945 17 import java.util.Iterator;
E 18 import java.util.List;
19 import java.util.Map;
20
21 /**
22  * http 工具类
23  */
24 public class HttpUtil {
25
26     /**multipart/form-data 格式发送数据时各个部分分隔符的前缀,必须为 --*/
27     private static final String BOUNDARY_PREFIX = "--";
28     /**回车换行,用于一行的结尾*/
29     private static final String LINE_END = "\r\n";
30
8bc3c9 31     public static String getInputStream(HttpServletRequest request) throws Exception {
C 32         ServletInputStream stream = null;
33         BufferedReader reader = null;
34         StringBuffer sb = new StringBuffer();
35         try {
36             stream = request.getInputStream();
37             // 获取响应
38             reader = new BufferedReader(new InputStreamReader(stream));
39             String line;
40             while ((line = reader.readLine()) != null) {
41                 sb.append(line);
42             }
43         } catch (IOException e) {
44             //logger.error(e);
45             throw new RuntimeException("读取返回支付接口数据流出现异常!");
46         } finally {
47             reader.close();
48         }
49         //logger.info("输入流返回的内容:" + sb.toString());
50         return sb.toString();
51     }
5c5945 52
E 53     public static String post(String requestUrl, String accessToken, String params)
54             throws Exception {
55         String contentType = "application/x-www-form-urlencoded";
56         return HttpUtil.post(requestUrl, accessToken, contentType, params);
57     }
58
59     public static String post(String requestUrl, String accessToken, String contentType, String params)
60             throws Exception {
61         String encoding = "UTF-8";
62         if (requestUrl.contains("nlp")) {
63             encoding = "GBK";
64         }
65         return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
66     }
67
68     public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
69             throws Exception {
70         String url = requestUrl + "?access_token=" + accessToken;
71         return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
72     }
73
74     public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
75             throws Exception {
76         URL url = new URL(generalUrl);
77         // 打开和URL之间的连接
78         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
79         connection.setRequestMethod("POST");
80         // 设置通用的请求属性
81         connection.setRequestProperty("Content-Type", contentType);
82         connection.setRequestProperty("Connection", "Keep-Alive");
83         connection.setUseCaches(false);
84         connection.setDoOutput(true);
85         connection.setDoInput(true);
86
87         // 得到请求的输出流对象
88         DataOutputStream out = new DataOutputStream(connection.getOutputStream());
89         out.write(params.getBytes(encoding));
90         out.flush();
91         out.close();
92
93         // 建立实际的连接
94         connection.connect();
95         // 获取所有响应头字段
96         Map<String, List<String>> headers = connection.getHeaderFields();
97         // 遍历所有的响应头字段
98         for (String key : headers.keySet()) {
99             System.err.println(key + "--->" + headers.get(key));
100         }
101         // 定义 BufferedReader输入流来读取URL的响应
102         BufferedReader in = null;
103         in = new BufferedReader(
104                 new InputStreamReader(connection.getInputStream(), encoding));
105         String result = "";
106         String getLine;
107         while ((getLine = in.readLine()) != null) {
108             result += getLine;
109         }
110         in.close();
111         System.err.println("result:" + result);
112         return result;
113     }
114
a1dba4 115     /**
E 116      * 带header的post请求
117      * @param generalUrl
118      * @param header
119      * @param params
120      * @return
121      * @throws Exception
122      */
123     public static String post(String generalUrl, Map<String, String> header, String params)
124             throws Exception {
125         URL url = new URL(generalUrl);
126         // 打开和URL之间的连接
127         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
128         connection.setRequestMethod("POST");
129         // 设置通用的请求属性
130         connection.setRequestProperty("Connection", "Keep-Alive");
131         if(header != null)
132         {
133             for(String key : header.keySet())
134             {
135                 connection.setRequestProperty(key, header.get(key));
136             }
137         }
138
139         connection.setUseCaches(false);
140         connection.setDoOutput(true);
141         connection.setDoInput(true);
142
143         // 得到请求的输出流对象
144         DataOutputStream out = new DataOutputStream(connection.getOutputStream());
145         out.write(params.getBytes("UTF-8"));
146         out.flush();
147         out.close();
148
149         // 建立实际的连接
150         connection.connect();
151         // 定义 BufferedReader输入流来读取URL的响应
152         BufferedReader in = null;
153         in = new BufferedReader(
154                 new InputStreamReader(connection.getInputStream(), "UTF-8"));
155         String result = "";
156         String getLine;
157         while ((getLine = in.readLine()) != null) {
158             result += getLine;
159         }
160         in.close();
161
162         return result;
163     }
164
5c5945 165     /** 请求http协议 获取信息工具 **/
E 166     public static JSONObject HttpURLUtil(String url, String data) {
167         HttpURLConnection con = null;
168         URL u = null;
169         String wxMsgXml = null;
170         JSONObject obj = null;
171         try {
172             u = new URL(url);
173             con = (HttpURLConnection) u.openConnection();
174             con.setRequestMethod("POST");
175             con.setDoOutput(true);
176             con.setDoInput(true);
177             con.setUseCaches(false);
178             con.setReadTimeout(5000);
179             con.setRequestProperty("Charset", "UTF-8");
180             con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
181
182             if (data != null) {
183                 OutputStream os = con.getOutputStream();
184                 os.write(data.getBytes("utf-8"));
185             }
186
187             if (con.getResponseCode() != 200)
188                 throw new RuntimeException("请求url失败");
189             // 读取返回内容
190             wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8");
191             obj = JSONObject.fromObject(wxMsgXml);
192             // //System.out.println("HttpURLUtil:"+wxMsgXml);
193         } catch (Exception e) {
194             e.printStackTrace();
195             obj = new JSONObject();
196             try {
197                 obj.put("status", 1);
198                 obj.put("errMsg", e.getMessage());
199             } catch (JSONException e1) {
200                 e1.printStackTrace();
201             }
202         } finally {
203             if (con != null) {
204                 con.disconnect();
205             }
206         }
207         return obj;
208     }
209
210
211     /** 请求http协议 获取信息工具 **/
212     public static JSONObject HttpURLUtilJson(String url, String data) {
213         HttpURLConnection con = null;
214         URL u = null;
215         String wxMsgXml = null;
216         JSONObject obj = null;
217         try {
218             u = new URL(url);
219             con = (HttpURLConnection) u.openConnection();
220             con.setRequestMethod("POST");
221             con.setDoOutput(true);
222             con.setDoInput(true);
223             con.setUseCaches(false);
224             con.setReadTimeout(5000);
225             con.setRequestProperty("Charset", "UTF-8");
226             con.setRequestProperty("Content-Type", "application/json");
227
228             if (data != null) {
229                 OutputStream os = con.getOutputStream();
230                 os.write(data.getBytes("utf-8"));
231             }
232
233             if (con.getResponseCode() != 200)
234                 throw new RuntimeException("请求url失败");
235             // 读取返回内容
236             wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8");
237             obj = JSONObject.fromObject(wxMsgXml);
238             // //System.out.println("HttpURLUtil:"+wxMsgXml);
239         } catch (Exception e) {
240             e.printStackTrace();
241         } finally {
242             if (con != null) {
243                 con.disconnect();
244             }
245         }
246         return obj;
247     }
248
249     /**
250      * post 请求:以表单方式提交数据
251      * <p>
252      * 由于 multipart/form-data 不是 http 标准内容,而是属于扩展类型,
253      * 因此需要自己构造数据结构,具体如下:
254      * <p>
255      * 1、首先,设置 Content-Type
256      * <p>
257      * Content-Type: multipart/form-data; boundary=${bound}
258      * <p>
259      * 其中${bound} 是一个占位符,代表我们规定的分割符,可以自己任意规定,
260      * 但为了避免和正常文本重复了,尽量要使用复杂一点的内容
261      * <p>
262      * 2、设置主体内容
263      * <p>
264      * --${bound}
265      * Content-Disposition: form-data; name="userName"
266      * <p>
267      * Andy
268      * --${bound}
269      * Content-Disposition: form-data; name="file"; filename="测试.excel"
270      * Content-Type: application/octet-stream
271      * <p>
272      * 文件内容
273      * --${bound}--
274      * <p>
275      * 其中${bound}是之前头信息中的分隔符,如果头信息中规定是123,那这里也要是123;
276      * 可以很容易看到,这个请求提是多个相同部分组成的:
277      * 每一部分都是以--加分隔符开始的,然后是该部分内容的描述信息,然后一个回车换行,然后是描述信息的具体内容;
278      * 如果传送的内容是一个文件的话,那么还会包含文件名信息以及文件内容类型。
279      * 上面第二部分是一个文件体的结构,最后以--分隔符--结尾,表示请求体结束
280      *
281      * @param urlStr      请求的url
282      * @param filePathMap key 参数名,value 文件的路径
283      * @param keyValues   普通参数的键值对
284      * @param headers
285      * @return
286      * @throws IOException
287      */
288     public static HttpResponse postFormData(String urlStr, Map<String, String> filePathMap, Map<String, Object> keyValues, Map<String, Object> headers) throws IOException {
289         HttpResponse response;
290         HttpURLConnection conn = getHttpURLConnection(urlStr, headers);
291         //分隔符,可以任意设置,这里设置为 MyBoundary+ 时间戳(尽量复杂点,避免和正文重复)
292         String boundary = "MyBoundary" + System.currentTimeMillis();
293         //设置 Content-Type 为 multipart/form-data; boundary=${boundary}
294         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
295
296         //发送参数数据
297         try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
298             //发送普通参数
299             if (keyValues != null && !keyValues.isEmpty()) {
300                 for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
301                     writeSimpleFormField(boundary, out, entry);
302                 }
303             }
304             //发送文件类型参数
305             if (filePathMap != null && !filePathMap.isEmpty()) {
306                 for (Map.Entry<String, String> filePath : filePathMap.entrySet()) {
307                     writeFile(filePath.getKey(), filePath.getValue(), boundary, out);
308                 }
309             }
310
311             //写结尾的分隔符--${boundary}--,然后回车换行
312             String endStr = BOUNDARY_PREFIX + boundary + BOUNDARY_PREFIX + LINE_END;
313             out.write(endStr.getBytes());
314         } catch (Exception e) {
315             e.printStackTrace();
316             response = new HttpResponse(500, e.getMessage());
317             return response;
318         }
319
320         return getHttpResponse(conn);
321     }
322
323     public static HttpResponse postFormData(String urlStr, Map<String, MultipartFile> filePathMap, Map<String, Object> keyValues) throws IOException {
324         HttpResponse response;
325         HttpURLConnection conn = getHttpURLConnection(urlStr, null);
326         //分隔符,可以任意设置,这里设置为 MyBoundary+ 时间戳(尽量复杂点,避免和正文重复)
327         String boundary = "MyBoundary" + System.currentTimeMillis();
328         //设置 Content-Type 为 multipart/form-data; boundary=${boundary}
329         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
330
331         //发送参数数据
332         try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
333             //发送普通参数
334             if (keyValues != null && !keyValues.isEmpty()) {
335                 for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
336                     writeSimpleFormField(boundary, out, entry);
337                 }
338             }
339             //发送文件类型参数
340             if (filePathMap != null && !filePathMap.isEmpty()) {
341                 for (Map.Entry<String, MultipartFile> filePath : filePathMap.entrySet()) {
342                     writeFile(filePath.getKey(), filePath.getValue(), boundary, out);
343                 }
344             }
345
346             //写结尾的分隔符--${boundary}--,然后回车换行
347             String endStr = BOUNDARY_PREFIX + boundary + BOUNDARY_PREFIX + LINE_END;
348             out.write(endStr.getBytes());
349         } catch (Exception e) {
350             response = new HttpResponse(500, e.getMessage());
351             return response;
352         }
353
354         return getHttpResponse(conn);
355     }
356
357     /**
358      * 获得连接对象
359      *
360      * @param urlStr
361      * @param headers
362      * @return
363      * @throws IOException
364      */
365     private static HttpURLConnection getHttpURLConnection(String urlStr, Map<String, Object> headers) throws IOException {
366         URL url = new URL(urlStr);
367         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
368         //设置超时时间
369         conn.setConnectTimeout(50000);
370         conn.setReadTimeout(50000);
371         //允许输入流
372         conn.setDoInput(true);
373         //允许输出流
374         conn.setDoOutput(true);
375         //不允许使用缓存
376         conn.setUseCaches(false);
377         //请求方式
378         conn.setRequestMethod("POST");
379         //设置编码 utf-8
380         conn.setRequestProperty("Charset", "UTF-8");
381         //设置为长连接
382         conn.setRequestProperty("connection", "keep-alive");
383
384         //设置其他自定义 headers
385         if (headers != null && !headers.isEmpty()) {
386             for (Map.Entry<String, Object> header : headers.entrySet()) {
387                 conn.setRequestProperty(header.getKey(), header.getValue().toString());
388             }
389         }
390
391         return conn;
392     }
393
394     private static HttpResponse getHttpResponse(HttpURLConnection conn) {
395         HttpResponse response;
396         try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
397             int responseCode = conn.getResponseCode();
398             StringBuilder responseContent = new StringBuilder();
399             String line;
400             while ((line = reader.readLine()) != null) {
401                 responseContent.append(line);
402             }
403             response = new HttpResponse(responseCode, responseContent.toString());
404         } catch (Exception e) {
405             e.printStackTrace();
406             response = new HttpResponse(500, e.getMessage());
407         }
408         return response;
409     }
410
411     /**
412      * 写文件类型的表单参数
413      *
414      * @param paramName 参数名
415      * @param filePath  文件路径
416      * @param boundary  分隔符
417      * @param out
418      * @throws IOException
419      */
420     private static void writeFile(String paramName, String filePath, String boundary,
421                                   DataOutputStream out) {
422         try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)))) {
423             /**
424              * 写分隔符--${boundary},并回车换行
425              */
426             String boundaryStr = BOUNDARY_PREFIX + boundary + LINE_END;
427             out.write(boundaryStr.getBytes());
428             /**
429              * 写描述信息(文件名设置为上传文件的文件名):
430              * 写 Content-Disposition: form-data; name="参数名"; filename="文件名",并回车换行
431              * 写 Content-Type: application/octet-stream,并两个回车换行
432              */
433             String fileName = new File(filePath).getName();
434             String contentDispositionStr = String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", paramName, fileName) + LINE_END;
435             out.write(contentDispositionStr.getBytes());
436             String contentType = "Content-Type: application/octet-stream" + LINE_END + LINE_END;
437             out.write(contentType.getBytes());
438
439             String line;
440             while ((line = fileReader.readLine()) != null) {
441                 out.write(line.getBytes());
442             }
443             //回车换行
444             out.write(LINE_END.getBytes());
445         } catch (Exception e) {
446             e.printStackTrace();
447         }
448     }
449
450     /**
451      * 写文件类型的表单参数
452      *
453      * @param paramName 参数名
454      * @param multipartFile  文件
455      * @param boundary  分隔符
456      * @param out
457      * @throws IOException
458      */
459     private static void writeFile(String paramName, MultipartFile multipartFile, String boundary,
460                                   DataOutputStream out) {
461
462         try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(multipartFile.getInputStream()))) {
463             /**
464              * 写分隔符--${boundary},并回车换行
465              */
466             String boundaryStr = BOUNDARY_PREFIX + boundary + LINE_END;
467             out.write(boundaryStr.getBytes());
468             /**
469              * 写描述信息(文件名设置为上传文件的文件名):
470              * 写 Content-Disposition: form-data; name="参数名"; filename="文件名",并回车换行
471              * 写 Content-Type: application/octet-stream,并两个回车换行
472              */
473             String fileName = multipartFile.getName();
474             String contentDispositionStr = String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", paramName, fileName) + LINE_END;
475             out.write(contentDispositionStr.getBytes());
476             String contentType = "Content-Type: application/octet-stream" + LINE_END + LINE_END;
477             out.write(contentType.getBytes());
478
479             String line;
480             while ((line = fileReader.readLine()) != null) {
481                 out.write(line.getBytes());
482             }
483             //回车换行
484             out.write(LINE_END.getBytes());
485         } catch (Exception e) {
486             e.printStackTrace();
487         }
488     }
489
490     /**
491      * 写普通的表单参数
492      *
493      * @param boundary 分隔符
494      * @param out
495      * @param entry    参数的键值对
496      * @throws IOException
497      */
498     private static void writeSimpleFormField(String boundary, DataOutputStream out, Map.Entry<String, Object> entry) throws IOException {
499         //写分隔符--${boundary},并回车换行
500         String boundaryStr = BOUNDARY_PREFIX + boundary + LINE_END;
501         out.write(boundaryStr.getBytes());
502         //写描述信息:Content-Disposition: form-data; name="参数名",并两个回车换行
503         String contentDispositionStr = String.format("Content-Disposition: form-data; name=\"%s\"", entry.getKey()) + LINE_END + LINE_END;
504         out.write(contentDispositionStr.getBytes());
505         //写具体内容:参数值,并回车换行
506         String valueStr = entry.getValue().toString() + LINE_END;
507         out.write(valueStr.getBytes());
508     }
509
510     public static String formUpload(String urlStr, Map<String, String> textMap,
511                                     Map<String, String> fileMap,String contentType) {
512         String res = "";
513         HttpURLConnection conn = null;
514         // boundary就是request头和上传文件内容的分隔符
515         String BOUNDARY = "---------------------------123821742118716";
516         try {
517             URL url = new URL(urlStr);
518             conn = (HttpURLConnection) url.openConnection();
519             conn.setConnectTimeout(5000);
520             conn.setReadTimeout(30000);
521             conn.setDoOutput(true);
522             conn.setDoInput(true);
523             conn.setUseCaches(false);
524             conn.setRequestMethod("POST");
525             conn.setRequestProperty("Connection", "Keep-Alive");
526             // conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
527             conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
528             OutputStream out = new DataOutputStream(conn.getOutputStream());
529             // text
530             if (textMap != null) {
531                 StringBuffer strBuf = new StringBuffer();
532                 Iterator iter = textMap.entrySet().iterator();
533                 while (iter.hasNext()) {
534                     Map.Entry entry = (Map.Entry) iter.next();
535                     String inputName = (String) entry.getKey();
536                     String inputValue = (String) entry.getValue();
537                     if (inputValue == null) {
538                         continue;
539                     }
540                     strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
541                     strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
542                     strBuf.append(inputValue);
543                 }
544                 out.write(strBuf.toString().getBytes());
545             }
546             // file
547             if (fileMap != null) {
548                 Iterator iter = fileMap.entrySet().iterator();
549                 while (iter.hasNext()) {
550                     Map.Entry entry = (Map.Entry) iter.next();
551                     String inputName = (String) entry.getKey();
552                     String inputValue = (String) entry.getValue();
553                     if (inputValue == null) {
554                         continue;
555                     }
556                     File file = new File(inputValue);
557                     String filename = file.getName();
558
559                     //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
560                     contentType = new MimetypesFileTypeMap().getContentType(file);
561                     //contentType非空采用filename匹配默认的图片类型
562                     if(!"".equals(contentType)){
563                         if (filename.endsWith(".png")) {
564                             contentType = "image/png";
565                         }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
566                             contentType = "image/jpeg";
567                         }else if (filename.endsWith(".gif")) {
568                             contentType = "image/gif";
569                         }else if (filename.endsWith(".ico")) {
570                             contentType = "image/image/x-icon";
571                         }
572                     }
573                     if (contentType == null || "".equals(contentType)) {
574                         contentType = "application/octet-stream";
575                     }
576                     StringBuffer strBuf = new StringBuffer();
577                     strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
578                     strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
579                     strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
580                     out.write(strBuf.toString().getBytes());
581                     DataInputStream in = new DataInputStream(new FileInputStream(file));
582                     int bytes = 0;
583                     byte[] bufferOut = new byte[1024];
584                     while ((bytes = in.read(bufferOut)) != -1) {
585                         out.write(bufferOut, 0, bytes);
586                     }
587                     in.close();
588                 }
589             }
590             byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
591             out.write(endData);
592             out.flush();
593             out.close();
594             // 读取返回数据
595             StringBuffer strBuf = new StringBuffer();
596             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
597             String line = null;
598             while ((line = reader.readLine()) != null) {
599                 strBuf.append(line).append("\n");
600             }
601             res = strBuf.toString();
602             reader.close();
603             reader = null;
604         } catch (Exception e) {
605             System.out.println("发送POST请求出错。" + urlStr);
606             e.printStackTrace();
607         } finally {
608             if (conn != null) {
609                 conn.disconnect();
610                 conn = null;
611             }
612         }
613         return res;
614     }
615 }