HttpClientUtils.java
14.4 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package com.wondertek.util;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("deprecation")
@Slf4j
public class HttpClientUtils {
private static HttpClient httpClient = null;
/**
* 生产HttpClient实例
* 公开,静态的工厂方法,需要使用时才去创建该单体
*
* @return
*/
public static HttpClient getHttpClient() {
if (httpClient == null) {
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
}
return httpClient;
}
/**
* POST方式调用
*
* @param url
* @param obj 参数为实体类对象
* @return 响应字符串
* @throws java.io.UnsupportedEncodingException
*/
public static String executeByPOST(String url, Object obj) {
log.info("启动http请求,url:{},发送内容:{}", url, JSONUtil.toJsonStr(obj));
try {
HttpResponse execute = HttpRequest.post(url).body(JSONUtil.toJsonStr(obj)).timeout(10000).execute();
if (execute.isOk()) {
String body = execute.body();
log.info("完成执行http请求,url:{},出参:{}", url, body);
return body;
} else {
log.info("完成执行http请求,url:{},出参:{}", url, execute.body());
}
} catch (Exception e) {
log.error("完成执行http请求,url:{},异常:请求体:{},错误信息:{}", url, obj,e.getMessage());
}
return null;
}
/**
* POST方式调用
*
* @param url
* @param obj 参数为实体类对象
* @return 响应字符串
* @throws java.io.UnsupportedEncodingException
*/
public static String executeByPOST(String url, String obj) {
log.info("启动http请求,url:{},发送内容:{}", url, obj);
try {
HttpResponse execute = HttpRequest.post(url).body(obj).timeout(10000).execute();
if (execute.isOk()) {
String body = execute.body();
log.info("完成执行http请求,url:{},出参:{}", url, body);
return body;
} else {
log.info("完成执行http请求,url:{},出参:{}", url, execute.body());
}
} catch (Exception e) {
log.error("完成执行http请求,url:{},异常:请求体:{},错误信息:{}", url, obj,e.getMessage());
}
return null;
}
public static Map<String,String> executeByPOST(String info,String url, String obj) {
log.info(info+"===>启动http请求,url:{},发送内容:{}", url, obj);
Map<String,String> resMap= new HashMap<>();
try {
HttpResponse execute = HttpRequest.post(url).body(obj).timeout(10000).execute();
if (execute.isOk()) {
String body = execute.body();
log.info(info+"===>完成执行http请求,url:{},出参:{}", url, body);
resMap.put("data",body);
resMap.put("code","200");
} else {
log.info(info+"===>完成执行http请求,url:{},出参:{}", url, execute.body());
resMap.put("data",execute.body());
resMap.put("code","500");
}
} catch (Exception e) {
log.error("完成执行http请求,url:{},异常:请求体:{},错误信息:{}", url, obj,e.getMessage());
}
return null;
}
public static String executeByPUT(String url, String obj) {
log.info("启动http请求,url:{},发送内容:{}", url, obj);
try {
HttpResponse execute = HttpRequest.put(url).body(obj).timeout(10000).execute();
if (execute.isOk()) {
String body = execute.body();
log.info("完成执行http请求,url:{},出参:{}", url, body);
return body;
} else {
log.info("完成执行http请求,url:{},出参:{}", url, execute.body());
}
} catch (Exception e) {
log.error("完成执行http请求,url:{},异常:请求体:{},错误信息:{}", url, obj,e.getMessage());
}
return null;
}
public static String executeByDELETE(String url, String obj) {
log.info("启动http请求,url:{},发送内容:{}", url, obj);
try {
HttpResponse execute = HttpRequest.delete(url).body(obj).timeout(10000).execute();
if (execute.isOk()) {
String body = execute.body();
log.info("完成执行http请求,url:{},出参:{}", url, body);
return body;
} else {
log.info("完成执行http请求,url:{},出参:{}", url, execute.body());
}
} catch (Exception e) {
log.error("完成执行http请求,url:{},异常:请求体:{},错误信息:{}", url, obj,e.getMessage());
}
return null;
}
/**
* POST方式调用
*
* @param url
* @param params 参数为NameValuePair键值对对象
* @return 响应字符串
* @throws java.io.UnsupportedEncodingException
*/
public static String executeByPOST(String url, List<NameValuePair> params) {
HttpClient httpclient = getHttpClient();
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(180000).build();
post.setConfig(requestConfig);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseJson = null;
try {
if (params != null) {
post.setEntity(new UrlEncodedFormEntity(params));
}
responseJson = httpclient.execute(post, responseHandler);
log.info("HttpClient POST请求结果:" + responseJson);
} catch (Exception e) {
log.info("HttpClient POST请求异常:" + e.getMessage());
} finally {
httpclient.getConnectionManager().closeExpiredConnections();
httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
}
return responseJson;
}
/**
* POST方式调用
*
* @param url
* @param xml 请求Json字符串
* @param headerMap 自定义头
* @return 响应字符串
* @throws java.io.UnsupportedEncodingException
*/
public static String executeByPOST(String url, String xml, Map<String,String> headerMap) {
log.info("启动http请求,url:{},发送内容:{},请求头:{}", url, xml, JSONUtil.toJsonStr(headerMap));
try {
HttpRequest request = HttpRequest.post(url);
if(null != headerMap) {
request.headerMap(headerMap, true);
}
HttpResponse execute = request.body(xml).timeout(10000).execute();
String body = execute.body();
log.info("完成执行http请求,url:{},出参:{}", url, body);
return body;
} catch (Exception e) {
log.error("完成执行http请求,url:{},异常:请求体:{},错误信息:{}", url, xml,e.getMessage());
throw e;
}
}
public static String executeByGET(String url, Object[] params) {
HttpClient httpclient = getHttpClient();
String messages = MessageFormat.format(url, params);
HttpGet get = new HttpGet(messages);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(180000).build();
get.setConfig(requestConfig);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseJson = null;
try {
responseJson = httpclient.execute(get, responseHandler);
} catch (Exception e) {
log.info("HttpClient GET请求异常,url:{},error:{}", messages, e.getMessage());
} finally {
httpclient.getConnectionManager().closeExpiredConnections();
httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
}
return responseJson;
}
public static String executeByGET(String url) {
String responseBody = null;
try {
log.info(">>>HTTP get请求,请求URL:" + url);
HttpRequest httpGet = HttpUtil.createGet(url);
httpGet.setConnectionTimeout(2000).setReadTimeout(5000);
HttpResponse response = httpGet.execute();
response.charset(Charset.defaultCharset());
if (response.isOk()) {
responseBody = response.body();
if (StringUtils.isNotBlank(responseBody)) {
log.info(">>>HTTP get请求,请求成功" + ",请求结果长度:" + responseBody.length());
}
}
} catch (Exception e) {
log.warn("HTTP get请求URL:" + url + ",请求异常:" + e.getMessage());
}
return responseBody;
/*
* HttpClient httpclient = getHttpClient();
*
* HttpParams params = httpClient.getParams();
* params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
*
* HttpGet get = new HttpGet(url);
* RequestConfig requestConfig =
* RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(5000).build()
* ;
* get.setConfig(requestConfig);
* ResponseHandler<String> responseHandler = new BasicResponseHandler();
* String responseJson = null;
* try {
* responseJson = httpclient.execute(get, responseHandler);
* log.info(">>>HttpClient请求URL:"+url+ ",请求结果长度:"+ responseJson.length());
* } catch (Exception e) {
* log.warn("HttpClient请求URL:"+url+",请求异常:" + e.getMessage());
* } finally {
* httpclient.getConnectionManager().closeExpiredConnections();
* httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
* }
* return responseJson;
*/
}
/** 仅限用于get请求,传递媒资id列表,其他格式未必适合
* get请求传参,传入url和list数组
* 如:http://localhost:8920/oes-csas-manage/es-operate/sync5?assetIds=20210261500049,20210261500053
* @Param [url, assetIdList]
* @return java.lang.String
**/
public static String executeByGET(String url, List<Long> assetIdList) {
HttpClient httpclient = getHttpClient();
StringBuilder buffer = new StringBuilder();
for (Long assetId : assetIdList) {
buffer.append(assetId).append(",");
}
String substring = buffer.substring(0, buffer.length()-1);
// String messages = MessageFormat.format(url, substring);
String messages = url+substring;
log.info("get请求 messages = " + messages);
HttpGet get = new HttpGet(messages);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(180000).build();
get.setConfig(requestConfig);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseJson = null;
try {
responseJson = httpclient.execute(get, responseHandler);
} catch (Exception e) {
log.info("HttpClient GET请求异常:" + e.getMessage());
} finally {
httpclient.getConnectionManager().closeExpiredConnections();
httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
}
return responseJson;
}
/**
* 带cookie的get请求
*
* @param url 请求路径
* @param cookie cookie
* @return 请求结果
*/
public static String executeByGET(String url, String cookie) {
String responseBody = null;
try {
log.info(">>>带cookie的HTTP请求,请求URL:" + url);
HttpRequest httpGet = HttpUtil.createGet(url);
httpGet.cookie(cookie);
httpGet.setConnectionTimeout(2000).setReadTimeout(5000);
HttpResponse response = httpGet.execute();
response.charset(Charset.defaultCharset());
if (response.isOk()) {
responseBody = response.body();
if (StringUtils.isNotBlank(responseBody)) {
log.info(">>>带cookie的HTTP请求,请求成功" + ",请求结果长度:" + responseBody.length());
}
}
} catch (Exception e) {
log.warn("HttpClient请求URL:" + url + ",请求异常:" + e.getMessage());
}
return responseBody;
/*
* HttpClient httpclient = getHttpClient();
*
* HttpParams params = httpClient.getParams();
* params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
*
* HttpGet get = new HttpGet(url);
* RequestConfig requestConfig =
* RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(5000).build()
* ;
* get.setConfig(requestConfig);
* ResponseHandler<String> responseHandler = new BasicResponseHandler();
* String responseJson = null;
* try {
* get.setHeader("Cookie",cookie);
* responseJson = httpclient.execute(get, responseHandler);
* log.info(">>>HttpClient请求URL:"+url+ ",请求结果长度:"+ responseJson.length());
* } catch (Exception e) {
* log.warn("HttpClient请求URL:"+url+",请求异常:" + e.getMessage());
* } finally {
* httpclient.getConnectionManager().closeExpiredConnections();
* httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
* }
* return responseJson;
*/
}
}