HttpClientUtil.java
17 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
package com.genersoft.iot.vmp.utils;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.*;
public class HttpClientUtil {
public static String post(String url, Map<String, String> params) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = postForm(url, params);
String body = null;
try {
CloseableHttpResponse response2 = httpclient.execute(post);
try {
HttpEntity entity2 = response2.getEntity();
body = EntityUtils.toString(entity2, "UTF-8");
EntityUtils.consume(entity2);
} finally {
response2.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return body;
}
public static String get(String url) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
String body = null;
try {
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
HttpEntity entity1 = response1.getEntity();
String charset = EntityUtils.getContentCharSet(entity1);
body = EntityUtils.toString(entity1);
EntityUtils.consume(entity1);
} finally {
response1.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return body;
}
/**
* @param url
* @param params
* @return
*/
private static HttpPost postForm(String url, Map<String, String> params) {
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return httpost;
}
public static String post(String url, String inMessageXml) {
System.out.println("url..." + url);
System.out.println("inMessageXml..." + inMessageXml);
//创建httpclient工具对象
HttpClient client = new HttpClient();
//创建post请求方法
PostMethod myPost = new PostMethod(url);
//设置请求超时时间
client.setConnectionTimeout(3000 * 1000);
String responseString = null;
try {
//设置请求头部类型
myPost.setRequestHeader("Content-Type", "text/xml");
myPost.setRequestHeader("charset", "utf-8");
//设置请求体,即xml文本内容,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式
myPost.setRequestEntity(new StringRequestEntity(inMessageXml, "text/xml", "utf-8"));
int statusCode = client.executeMethod(myPost);
//只有请求成功200了,才做处理
if (statusCode == HttpStatus.SC_OK) {
InputStream inputStream = myPost.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
responseString = stringBuffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myPost.releaseConnection();
((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
}
return responseString;
}
public static String doPost(String url, Object data) {
String jsonData = JSON.toJSONString(data);
//String jsonData = JSONUtils.toJson(data);
System.out.println("url..." + url);
System.out.println("inMessageXml..." + data);
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
try {
StringEntity s = new StringEntity(jsonData, "utf-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(res.getEntity());
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* HttpURLConnection方式 模拟Http Get请求
*
* @param urlStr 请求路径
* @param paramMap 请求参数
* @return
* @throws Exception
*/
public static String get(String urlStr, Map<String, String> paramMap) throws Exception {
urlStr = urlStr + "?" + getParamString(paramMap);
HttpURLConnection conn = null;
try {
//创建URL对象
URL url = new URL(urlStr);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用的请求属性
setHttpUrlConnection(conn, "GET");
//建立实际的连接
conn.connect();
//获取响应的内容
return readResponseContent(conn.getInputStream());
} finally {
if (null != conn)
conn.disconnect();
}
}
/**
* HttpURLConnection方式 模拟Http Post请求
*
* @param urlStr 请求路径
* @return
* @throws Exception
*/
public static String postMap(String urlStr, Object object) throws Exception {
HttpURLConnection conn = null;
PrintWriter writer = null;
try {
//创建URL对象
URL url = new URL(urlStr);
//获取请求参数
Map<String, String> params = objectToMap(object);
String param = getParamString(params);
//获取URL连接
System.out.println("requestUrl:" + urlStr);
System.out.println("outputStr:" + param);
conn = (HttpURLConnection) url.openConnection();
//设置通用请求属性
setHttpUrlConnection(conn, "POST");
//建立实际的连接
conn.connect();
//将请求参数写入请求字符流中
writer = new PrintWriter(conn.getOutputStream());
writer.print(param);
writer.flush();
//读取响应的内容
return readResponseContent(conn.getInputStream());
} finally {
if (null != conn)
conn.disconnect();
if (null != writer)
writer.close();
}
}
/**
* HttpURLConnection方式 模拟Http Post请求
*
* @param urlStr 请求路径
* @return
* @throws Exception
*/
public static String postByMap(String urlStr, Map<String, String> params) throws Exception {
HttpURLConnection conn = null;
PrintWriter writer = null;
try {
//创建URL对象
URL url = new URL(urlStr);
//获取请求参数
String param = getParamString(params);
//获取URL连接
System.out.println("requestUrl:" + urlStr);
System.out.println("outputStr:" + param);
conn = (HttpURLConnection) url.openConnection();
//设置通用请求属性
setHttpUrlConnection(conn, "POST");
//建立实际的连接
conn.connect();
//将请求参数写入请求字符流中
writer = new PrintWriter(conn.getOutputStream());
writer.print(param);
writer.flush();
//读取响应的内容
return readResponseContent(conn.getInputStream());
} finally {
if (null != conn)
conn.disconnect();
if (null != writer)
writer.close();
}
}
/**
* 转换对象为map
*
* @param object
* @param ignore
* @return
*/
public static Map<String, String> objectToMap(Object object, String... ignore) {
Map<String, String> tempMap = new LinkedHashMap<String, String>();
//获取本类的Fields
for (Field f : object.getClass().getDeclaredFields()) {
if (!f.isAccessible()) {
f.setAccessible(true);
}
boolean ig = false;
if (ignore != null && ignore.length > 0) {
for (String i : ignore) {
if (i.equals(f.getName())) {
ig = true;
break;
}
}
}
if (ig) {
continue;
} else {
Object o = null;
try {
o = f.get(object);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
tempMap.put(f.getName(), o == null ? "" : o.toString());
}
}
//获取基类的Fields
for (Field f : object.getClass().getFields()) {
if (!f.isAccessible()) {
f.setAccessible(true);
}
boolean ig = false;
if (ignore != null && ignore.length > 0) {
for (String i : ignore) {
if (i.equals(f.getName())) {
ig = true;
break;
}
}
}
if (ig) {
continue;
} else {
Object o = null;
try {
o = f.get(object);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
tempMap.put(f.getName(), o == null ? "" : o.toString());
}
}
return tempMap;
}
/**
* 将参数转为路径字符串
*
* @param paramMap 参数
* @return
*/
private static String getParamString(Map<String, String> paramMap) {
if (null == paramMap || paramMap.isEmpty()) {
return "";
}
StringBuilder builder = new StringBuilder();
for (String key : paramMap.keySet()) {
if (!key.equals("pd")) {
if (StringUtils.isNotEmpty(paramMap.get(key))) {
//传入值不为空 拼接字符串
builder.append("&").append(key).append("=").append(paramMap.get(key));
} else {
builder.append("&");
}
}
}
return new String(builder.deleteCharAt(0).toString());
}
/**
* 读取响应字节流并将之转为字符串
*
* @param in 要读取的字节流
* @return
* @throws IOException
*/
private static String readResponseContent(InputStream in) throws IOException {
Reader reader = null;
StringBuilder content = new StringBuilder();
try {
reader = new InputStreamReader(in, "utf-8");
char[] buffer = new char[1024];
int head = 0;
while ((head = reader.read(buffer)) > 0) {
content.append(new String(buffer, 0, head));
}
String result = content.toString();
System.out.println("readResponseContent.." + result);
return result;
} finally {
if (null != in) {
in.close();
}
if (null != reader) {
reader.close();
}
}
}
/**
* 设置Http连接属性
*
* @param conn http连接
* @return
* @throws ProtocolException
* @throws Exception
*/
private static void setHttpUrlConnection(HttpURLConnection conn,
String requestMethod) throws ProtocolException {
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-encoding", "UTF-8");
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
if (null != requestMethod && "POST".equals(requestMethod)) {
conn.setDoOutput(true);
conn.setDoInput(true);
}
}
/**
* 新http请求
*
* @param requestUrl
* @param requestMethod
* @param object
* @return
*/
public static String httpRequest(String requestUrl, String requestMethod, Object object) {
//获取请求参数
Map<String, String> params = objectToMap(object);
String outputStr = getParamString(params);
System.out.println("requestUrl:" + requestUrl);
System.out.println("outputStr:" + outputStr);
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (ConnectException ce) {
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("返回:" + buffer.toString());
return buffer.toString();
}
}