提交 | 用户 | age
|
6c1bfc
|
1 |
package com.platform.util; |
C |
2 |
|
|
3 |
import com.hx.util.StringUtils; |
|
4 |
import org.apache.commons.io.IOUtils; |
|
5 |
|
|
6 |
import java.io.OutputStream; |
|
7 |
import java.net.HttpURLConnection; |
|
8 |
import java.net.URL; |
|
9 |
import java.util.Map; |
|
10 |
|
|
11 |
/** |
|
12 |
* http 工具类 |
|
13 |
*/ |
|
14 |
public class HttpPlatformUtil { |
|
15 |
|
|
16 |
/** 请求http协议 获取信息工具 |
|
17 |
* @param url 请求链接 |
|
18 |
* @param data 请求数据(body) |
|
19 |
* @param keyValues form表单数据 key参数名称,value参数值 |
|
20 |
* @param header 请求头 |
|
21 |
* @param requestMethod 请求头方法,默认POST |
|
22 |
* @return |
|
23 |
*/ |
|
24 |
public static String HttpURLUtilJson(String url, String data,Map<String,Object> keyValues,Map<String,String> header,String requestMethod) { |
|
25 |
HttpURLConnection con = null; |
|
26 |
URL u = null; |
|
27 |
String wxMsgXml = null; |
|
28 |
try { |
|
29 |
StringBuilder dataP = new StringBuilder(); |
|
30 |
if (keyValues != null && !keyValues.isEmpty()) { |
|
31 |
for (Map.Entry<String, Object> entry : keyValues.entrySet()) { |
|
32 |
dataP.append((String)entry.getKey()).append("="); |
|
33 |
dataP.append(entry.getValue()); |
|
34 |
dataP.append("&"); |
|
35 |
} |
|
36 |
dataP.deleteCharAt(dataP.length() - 1); |
|
37 |
url = url+"?"+dataP; |
|
38 |
} |
|
39 |
|
|
40 |
if(StringUtils.isEmpty(requestMethod)){ |
|
41 |
requestMethod = "POST"; |
|
42 |
} |
|
43 |
u = new URL(url); |
|
44 |
con = (HttpURLConnection) u.openConnection(); |
|
45 |
con.setRequestMethod(requestMethod); |
|
46 |
con.setDoOutput(true); |
|
47 |
con.setDoInput(true); |
|
48 |
con.setUseCaches(false); |
|
49 |
con.setReadTimeout(5000); |
|
50 |
con.setRequestProperty("Charset", "UTF-8"); |
|
51 |
con.setRequestProperty("Content-Type", "application/json"); |
|
52 |
if(header != null){ |
|
53 |
for (Map.Entry<String, String> entry : header.entrySet()) { |
|
54 |
con.setRequestProperty(entry.getKey(),entry.getValue()); |
|
55 |
} |
|
56 |
} |
|
57 |
|
|
58 |
if (data != null) { |
|
59 |
OutputStream os = con.getOutputStream(); |
|
60 |
os.write(data.getBytes("utf-8")); |
|
61 |
} |
|
62 |
|
|
63 |
if (con.getResponseCode() != 200){ |
|
64 |
throw new RuntimeException("请求url失败"); |
|
65 |
} |
|
66 |
// 读取返回内容 |
|
67 |
wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); |
|
68 |
// //System.out.println("HttpURLUtil:"+wxMsgXml); |
|
69 |
} catch (Exception e) { |
|
70 |
e.printStackTrace(); |
|
71 |
} finally { |
|
72 |
if (con != null) { |
|
73 |
con.disconnect(); |
|
74 |
} |
|
75 |
} |
|
76 |
return wxMsgXml; |
|
77 |
} |
|
78 |
|
|
79 |
} |