HttpUtils.java
21.9 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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
package com.lhcredit.common.utils.http;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.experimental.var;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.WebRequest;
/**
* 通用http发送方法
*/
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url + "?" + param;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
/**
* 向htpps URL 发送POST方法的请求
*
* @param url
* @param param
* @return
*/
public static String sendSSLPost(String url, String param) {
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try {
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null) {
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
} catch (ConnectException e) {
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
}
/**
* urlEncode编码
*
* @param content
* @return
*/
public static String urlEncode(String content) {
try {
return URLEncoder.encode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* urlDecode解码
*
* @param content
* @return
*/
public static String urlDecode(String content) {
try {
return URLDecoder.decode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 证书信任管理器类
*/
private static class TrustAnyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static String send(String url, JSONArray jsonObject, String encoding) {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
// System.out.println("请求地址:"+url);
// System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
try {
body = EntityUtils.toString(entity, encoding);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
//释放链接
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
// public static void main(String[] args) {
// JSONArray jsonArray=new JSONArray();
//
// JSONObject j=new JSONObject();
// j.put("proCode","ddd");
// j.put("orgName","ddd");
// jsonArray.add(j);
// try {
// send("http://192.168.4.205:8081/web/taskMain/addTaskMain",jsonArray,"utf-8");
// } catch (ParseException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
public static String post(String qrcodeUrl,String access_token, String page, String scene, Integer width) {
// String qrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit"; // 获取小程序码的接口头部
String url = qrcodeUrl+"?access_token="+access_token; // 拼接完整的URl
Map<String, Object> requestParam = new HashMap<String,Object>(); // 小程序的参数可查看官方文档
if(page!= null) requestParam.put("page", page); // 扫码后需要跳转的页面
if(scene!= null) requestParam.put("scene", scene); // 携带的参数
if(width!= null) requestParam.put("width", width); // 二维码的宽度
String param = JSON.toJSONString(requestParam);
// 使用 RestTemplate 出现的问题,用该类代码会更简洁
// rest debugger发过来的content-type为application/json,而jq的多了charset=utf-8
// Could not read document: Invalid UTF-8 middle byte 0xff
/*JSONObject jsonObject =
restTemplate.postForObject(url, param, JSONObject.class);
System.out.println(jsonObject.toJSONString());*/
HttpURLConnection conn = null;
BufferedReader bufferedReader = null;
PrintWriter out = null;
InputStream in = null;
ByteArrayOutputStream bos = null;
String base64String = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 超时设置,防止 网络异常的情况下,可能会导致程序僵死而不继续往下执行
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
in = conn.getInputStream(); // 得到图片的二进制内容
int leng = in.available(); // 获取二进制流的长度,该方法不准确
if(leng < 1000){ // 出现错误时,获取字符长度就一百不到,图片的话有几万的长度
// 定义BufferedReader输入流来读取URL的响应
bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// 清空 access_token 缓存
// CacheManagerImpl cacheManagerImpl = CacheManagerImpl.getInstance();
// cacheManagerImpl.clearByKey("access_token");
return result;
}
// 修改图片的分辨率,分辨率太大打印纸不够大
//BufferedInputStream in2 = new BufferedInputStream(conn.getInputStream());
// 将文件二进制流修改为图片流
Image srcImg = ImageIO.read(in);
// 构建图片流
BufferedImage buffImg = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB);
//绘制改变尺寸后的图
buffImg.getGraphics().drawImage(srcImg.getScaledInstance(width, width, Image.SCALE_SMOOTH), 0, 0, null);
// 将图片流修改为文件二进制流
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImg, "png", os);
in = new ByteArrayInputStream(os.toByteArray());
// 刷新,将重置为类似于首次创建时的状态
buffImg.flush();
srcImg.flush();
// 设null是告诉jvm此资源可以回收
buffImg = null; // 该io流不存在关闭函数
srcImg = null; // 该io流不存在关闭函数
os.close();
bos = new ByteArrayOutputStream();
byte[] b1 = new byte[1024];
int len = -1;
while((len = in.read(b1)) != -1) {
bos.write(b1, 0, len);
}
byte[] fileByte = bos.toByteArray(); // 转换为字节数组,方便转换成base64编码
//BASE64Encoder encoder = new BASE64Encoder(); // import sun.misc.BASE64Encoder; 该类包为内部专用以后可能会删除,sun公司
// 对字节数组转换成Base64字符串
//base64String = encoder.encode(fileByte);
base64String = Base64.encodeBase64String(fileByte); // import org.apache.commons.codec.binary.Base64;
} catch (Exception e) {
}
//使用finally块来关闭输出流、输入流
finally{
try {
if(bufferedReader != null){
bufferedReader.close();
}
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
if(bos != null){
bos.close();
}
if(conn !=null){
conn.disconnect();
conn = null;
}
//让系统回收资源,但不一定是回收刚才设成null的资源,可能是回收其他没用的资源。
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
return base64String; // 将base64格式的图片发送到前端
}
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @return 所代表远程资源的响应结果
*/
public static String sendGetFromDNA(String url) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url+"&key=xygj";
// log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
// connection.setRequestProperty("Token", cstToken);
connection.setRequestProperty("Token", "f21bcdd7-90a7-4d39-9bed-56bed670314a");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// connection.setRequestProperty("Authorization", LhcreditConfig.getToken());
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
// log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url, ex);
}
}
return result.toString();
}
public static String sendGet(String url,String param,String token) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url+"?"+param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Token", token);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// connection.setRequestProperty("Accept-Charset", "utf-8");
// connection.setRequestProperty("contentType", "utf-8");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url, ex);
}
}
return result.toString();
}
}