forked from AlEinstein/javaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPUtil.java
More file actions
352 lines (314 loc) · 14.7 KB
/
Copy pathHTTPUtil.java
File metadata and controls
352 lines (314 loc) · 14.7 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package common.utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* @author xma
*/
public class HTTPUtil {
private static Logger logger = LoggerFactory.getLogger(HTTPUtil.class);
private static Integer SUCCESS = 200;
private static ContentType formUTF8 = ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8);
/**
* 发送POST请求
*
* @param contentType 请求头的type
* @param url 请求的地址
* @param params 参数
* @param socketTimeout 接口超时
* @param connectTimeout 连接超时
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendPost(ContentType contentType, String url, Map<String, Object> params, Integer socketTimeout, Integer connectTimeout) throws IOException {
List<NameValuePair> parameters = new ArrayList<>();
if (params != null) {
for (String key : params.keySet()) {
if (params.get(key) != null) {
parameters.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
}
HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
};
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(1000)
.setSocketTimeout(socketTimeout).setMaxRedirects(0).build();
CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(requestRetryHandler).setDefaultRequestConfig(requestConfig).build();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", contentType.toString());
post.setEntity(new UrlEncodedFormEntity(parameters, contentType.getCharset()));
CloseableHttpResponse response = httpclient.execute(post);
checkStatus(response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, contentType.getCharset());
}
/**
* 发送POST请求,默认Content-Type application/json; charset=UTF-8
*
* @param url 请求的地址
* @param body body参数
* @param socketTimeout 接口超时
* @param connectTimeout 连接超时
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendBodyPost(String url, String body, Integer socketTimeout, Integer connectTimeout) throws IOException {
return sendBodyPost(ContentType.APPLICATION_JSON, url, body, socketTimeout, connectTimeout);
}
public static String sendBodyPost(ContentType contentType, String url, String body, Integer socketTimeout, Integer connectTimeout) throws IOException {
HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
};
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(1000)
.setSocketTimeout(socketTimeout).setMaxRedirects(0).build();
CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(requestRetryHandler).setDefaultRequestConfig(requestConfig).build();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", contentType.toString());
post.setEntity(new StringEntity(body, contentType));
CloseableHttpResponse response = httpclient.execute(post);
checkStatus(response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, contentType.getCharset());
}
public static String sendBodyPost(ContentType contentType, String url, String body, String platform, String requestType) throws IOException {
logger.info("请求" + platform + " 地址:" + url + " 请求类型:" + requestType + " body信息:" + body);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String res = sendBodyPost(contentType, url, body, 20000, 20000);
stopWatch.stop();
logger.info("返回值为:" + res);
logger.info(platform + " " + requestType + " 本次请求耗时:(duration:" + stopWatch.getTime() + ")");
return res;
}
/**
* 发送HTTP POST请求,默认超时20s,默认Content-Type application/json; charset=UTF-8
*
* @param url 请求的地址
* @param body body参数
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendBodyPost(String url, String body) throws IOException {
return sendBodyPost(url, body, 20000, 20000);
}
/**
* 发送HTTP POST请求,默认超时20s,默认Content-Type application/json; charset=UTF-8
*
* @param url 请求的地址
* @param body body参数
* @param platform 平台类型
* @param requestType 请求类型
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendBodyPost(String url, String body, String platform, String requestType) throws IOException {
logger.info("请求:" + platform + " 请求类型:" + requestType + " 地址:" + url + " 参数:" + body);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String res = sendBodyPost(url, body);
stopWatch.stop();
logger.info("返回值为:" + res);
logger.info(platform + " " + requestType + " 本次请求耗时:(duration:" + stopWatch.getTime() + ")");
return res;
}
/**
* 发送HTTP POST请求,默认超时20s,默认Content-Type application/x-www-form-urlencoded; charset=UTF-8
*
* @param url 请求的地址
* @param params 参数
* @param platform 平台类型
* @param requestType 请求类型
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendPost(String url, Map<String, Object> params, String platform, String requestType) throws IOException {
return sendPost(formUTF8, url, params, platform, requestType);
}
/**
* 发送HTTP POST请求,默认超时20s,默认Content-Type application/x-www-form-urlencoded; charset=UTF-8
*
* @param url 请求的地址
* @param platform 平台类型
* @param requestType 请求类型
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendPost(String url, String platform, String requestType) throws IOException {
logger.info("请求" + platform + " 地址:" + url + " 请求类型:" + requestType);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String res = sendPost(formUTF8, url, null, 20000, 20000);
stopWatch.stop();
logger.info("返回值为:" + res);
logger.info(platform + " " + requestType + " 本次请求耗时:(duration:" + stopWatch.getTime() + ")");
return res;
}
/**
* 发送HTTP POST请求,默认超时20s,默认Content-Type application/x-www-form-urlencoded; charset=UTF-8
*
* @param url 请求的地址
* @param params 参数
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendPost(String url, Map<String, Object> params) throws IOException {
return sendPost(formUTF8, url, params, 20000, 20000);
}
/**
* 发送HTTP POST请求,默认超时20s
*
* @param contentType 请求头的type
* @param url 请求的地址
* @param params 参数
* @return 返回HTTP返回的信息
* @throws IOException HTTP异常
*/
public static String sendPost(ContentType contentType, String url, Map<String, Object> params) throws IOException {
return sendPost(contentType, url, params, 20000, 20000);
}
public static String sendPost(ContentType contentType, String url, Map<String, Object> params, String platform, String requestType) throws IOException {
logger.info("请求:" + platform + " 请求类型:" + requestType + " 地址:" + url + " 参数:" + JSON.toJSONString(params));
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String res = sendPost(contentType, url, params, 20000, 20000);
stopWatch.stop();
logger.info("返回值为:" + res);
logger.info(platform + " " + requestType + " 本次请求耗时:(duration:" + stopWatch.getTime() + ")");
return res;
}
public static String sendGet(String url, Map<String, Object> params, String platform, String requestType) throws IOException {
logger.info("请求:" + platform + " 请求类型:" + requestType + " 地址:" + url + " 参数:" + JSON.toJSONString(params));
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String res = sendGet(url, params, 20000);
stopWatch.stop();
logger.info("返回值为:" + res);
logger.info(platform + " " + requestType + " 本次请求耗时:(duration:" + stopWatch.getTime() + ")");
return res;
}
public static String sendGet(String url, String platform, String requestType) throws IOException {
logger.info("请求:" + platform + " 请求类型:" + requestType + " 地址:" + url);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String res = sendGet(url);
stopWatch.stop();
logger.info("返回值为:" + res);
logger.info(platform + " " + requestType + " 本次请求耗时:(duration:" + stopWatch.getTime() + ")");
return res;
}
public static String sendGet(String url, Map<String, Object> params) throws IOException {
return sendGet(url, params, 20000);
}
public static String sendGet(String url, Integer timeout) throws IOException {
return sendGet(url, null, timeout);
}
public static String sendGet(String url) throws IOException {
return sendGet(url, null, 20000);
}
public static String sendGet(String url, Map<String, Object> params, Integer timeout) throws IOException {
String realUrl = url + getUrl(url.contains("?"), params);
HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
};
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(timeout).setConnectionRequestTimeout(1000)
.setSocketTimeout(timeout).setMaxRedirects(0).build();
CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(requestRetryHandler).setDefaultRequestConfig(requestConfig).build();
HttpGet get = new HttpGet(realUrl);
CloseableHttpResponse response = httpclient.execute(get);
checkStatus(response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
public static String getUrl(Boolean notFirst, Map<String, Object> systemMap) throws UnsupportedEncodingException {
if (systemMap == null || systemMap.size() == 0) {
return StringUtils.EMPTY;
}
StringBuilder url = new StringBuilder();
boolean isFirst = !notFirst;
for (String key : systemMap.keySet()) {
String split = "&";
if (isFirst) {
isFirst = false;
split = "?";
}
if (systemMap.get(key) != null) {
url.append(split).append(key).append("=").append(URLEncoder.encode(systemMap.get(key).toString(), "UTF-8"));
}
}
return url.toString();
}
private static void checkStatus(Integer status) throws IOException {
if (!Objects.equals(status, SUCCESS)) {
throw new IOException(String.valueOf(status));
}
}
public static String buildParamStr(HashMap<String, String> param) {
String paramStr = "";
Object[] keyArray = param.keySet().toArray();
for (int i = 0; i < keyArray.length; i++) {
String key = (String) keyArray[i];
if (0 == i) {
paramStr += (key + "=" + param.get(key));
} else {
paramStr += ("&" + key + "=" + param.get(key));
}
}
return paramStr;
}
public static String buildParamStrWithEncode(HashMap<String, String> param) throws UnsupportedEncodingException {
String paramStr = "";
Object[] keyArray = param.keySet().toArray();
for (int i = 0; i < keyArray.length; i++) {
String key = (String) keyArray[i];
if (0 == i) {
paramStr += (URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(param.get(key), "UTF-8"));
} else {
paramStr += ("&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(param.get(key), "UTF-8"));
}
}
return paramStr;
}
public static String getRequestBody(InputStream inputStream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "utf-8");
return writer.toString();
}
}