HTTPHelper.java
9.02 KB
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
package com.uccc.number.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
/**
* Created by bert on 2021-10-26 15:53
*/
public class HTTPHelper {
// slf4j日志记录器
private static final Logger LOG = LoggerFactory.getLogger(HTTPHelper.class);
/***
* 向指定URL发送GET方法的请求
*
* @param apiUrl
* @param encoding
* @return
* @throws Exception
*/
public static String sendGet(String apiUrl, LinkedHashMap<String, String> headers,
String encoding) throws Exception {
// 获得响应内容
String http_RespContent = null;
HttpURLConnection httpURLConnection = null;
int http_StatusCode = 0;
String http_RespMessage = null;
try {
LOG.info(">>>> 实际请求Url: " + apiUrl);
// 建立连接
URL url = new URL(apiUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
// 需要输出
httpURLConnection.setDoOutput(true);
// 需要输入
httpURLConnection.setDoInput(true);
// 不允许缓存
httpURLConnection.setUseCaches(false);
// HTTP请求方式
httpURLConnection.setRequestMethod("GET");
// 设置Headers
if (null != headers) {
for (String key : headers.keySet()) {
httpURLConnection.setRequestProperty(key, headers.get(key));
}
}
// 连接会话
httpURLConnection.connect();
// 获得响应状态(HTTP状态码)
http_StatusCode = httpURLConnection.getResponseCode();
// 获得响应消息(HTTP状态码描述)
http_RespMessage = httpURLConnection.getResponseMessage();
// 获得响应内容
if (HttpURLConnection.HTTP_OK == http_StatusCode) {
// 返回响应结果
http_RespContent = getResponseContent(httpURLConnection);
} else {
// 返回非200状态时响应结果
http_RespContent = getErrorResponseContent(httpURLConnection);
String msg =
MessageFormat.format("请求失败: Http状态码 = {0} , {1}", http_StatusCode, http_RespMessage);
LOG.info(msg);
}
} catch (UnknownHostException e) {
String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} catch (MalformedURLException e) {
String message = MessageFormat.format("格式错误的URL: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} catch (IOException e) {
String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} catch (Exception e) {
String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} finally {
if (null != httpURLConnection) {
httpURLConnection.disconnect();
}
}
return http_RespContent;
}
/***
* 向指定URL发送POST方法的请求
*
* @param apiUrl
* @param data
* @param encoding
* @return
* @throws Exception
*/
public static String sendPOST(String apiUrl, String data, LinkedHashMap<String, String> headers,
String encoding) throws Exception {
// 获得响应内容
String http_RespContent = null;
HttpURLConnection httpURLConnection = null;
int http_StatusCode = 0;
String http_RespMessage = null;
try {
// 建立连接
URL url = new URL(apiUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
// 需要输出
httpURLConnection.setDoOutput(true);
// 需要输入
httpURLConnection.setDoInput(true);
// 不允许缓存
httpURLConnection.setUseCaches(false);
// HTTP请求方式
httpURLConnection.setRequestMethod("POST");
// 设置Headers
if (null != headers) {
for (String key : headers.keySet()) {
httpURLConnection.setRequestProperty(key, headers.get(key));
}
}
// 连接会话
httpURLConnection.connect();
// 建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
// 设置请求参数
dos.write(data.getBytes(encoding));
dos.flush();
dos.close();
// 获得响应状态(HTTP状态码)
http_StatusCode = httpURLConnection.getResponseCode();
// 获得响应消息(HTTP状态码描述)
http_RespMessage = httpURLConnection.getResponseMessage();
// 获得响应内容
if (HttpURLConnection.HTTP_OK == http_StatusCode) {
// 返回响应结果
http_RespContent = getResponseContent(httpURLConnection);
} else {
// 返回非200状态时响应结果
http_RespContent = getErrorResponseContent(httpURLConnection);
String msg =
MessageFormat.format("请求失败: Http状态码 = {0} , {1}", http_StatusCode, http_RespMessage);
LOG.info(msg);
}
} catch (UnknownHostException e) {
String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} catch (MalformedURLException e) {
String message = MessageFormat.format("格式错误的URL: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} catch (IOException e) {
String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} catch (Exception e) {
String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
Exception ex = new Exception(message);
ex.initCause(e);
throw ex;
} finally {
if (null != httpURLConnection) {
httpURLConnection.disconnect();
}
}
return http_RespContent;
}
/***
* 读取HttpResponse响应内容
*
* @param httpURLConnection
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static String getResponseContent(HttpURLConnection httpURLConnection)
throws UnsupportedEncodingException, IOException {
StringBuffer contentBuffer = null;
BufferedReader responseReader = null;
try {
contentBuffer = new StringBuffer();
String readLine = null;
responseReader =
new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
contentBuffer.append(readLine);
}
} finally {
if (null != responseReader) {
responseReader.close();
}
}
return contentBuffer.toString();
}
/***
* 读取HttpResponse响应内容
*
* @param httpURLConnection
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static String getErrorResponseContent(HttpURLConnection httpURLConnection)
throws UnsupportedEncodingException, IOException {
StringBuffer contentBuffer = null;
BufferedReader responseReader = null;
try {
contentBuffer = new StringBuffer();
String readLine = null;
responseReader =
new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
contentBuffer.append(readLine);
}
} finally {
if (null != responseReader) {
responseReader.close();
}
}
return contentBuffer.toString();
}
}