Utils-HttpClient工具类

  HttpClient工具使用示例,作为工具类备用。用的是比较新的4.5.3版本。

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
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wechatTicket.utils.ContentTypeConstant;
import com.wechatTicket.utils.MyX509TrustManager;

public class HttpClientUtils {

private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

private static RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();

/**
* 创建https连接
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}

/**
* 发送 get 请求(HTTPS),K-V形式
* @param url
* @param params
* @return jsonString
*/
public static String doGetSSL(String url, Map<String, Object> params){
String queryString = toQueryString(params);
CloseableHttpClient httpClient = createSSLClientDefault();
HttpGet httpGet = new HttpGet();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
String result = null;
try {
httpGet.setURI(new URI(url + "?" + queryString.toString()));
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("HttpGet方式请求失败!状态码:" + statusCode);
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
result = EntityUtils.toString(entity, "utf-8");
logger.info("HttpGet方式请求成功!返回结果:{}", result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

/**
* 发送 post 请求(HTTPS),K-V形式
* @param url
* @param json
* @return jsonString
*/
public static String doPostSSL(String url, Object json){
CloseableHttpClient httpClient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
String result = null;
try {
StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("HttpGet方式请求失败!状态码:" + statusCode);
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
result = EntityUtils.toString(entity, "utf-8");
logger.info("HttpGet方式请求成功!返回结果:{}", result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

/**
* httpURLConnection post请求方法
* @param requestUrl
* @param reqBody
* @return
*/
public static String httpsRequest(String requestUrl, String reqBody){
String UTF8 = "UTF-8";
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer = null;
String resp;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(10*1000);
httpURLConnection.setReadTimeout(10*1000);
httpURLConnection.connect();
outputStream = httpURLConnection.getOutputStream();
outputStream.write(reqBody.getBytes(UTF8));

inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, UTF8));
stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
resp = stringBuffer.toString();
return resp;
} catch (Exception e) {
System.out.println("https请求异常:{}"+ e.getMessage());
}finally {
if (stringBuffer!=null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}


/**
* 发送 get 请求(HTTPS) 获取下载流
* @param url
* @param params
* @return byte[]
*/
public static byte[] doGetSSLDown(String url, Map<String, Object> params){
String queryString = toQueryString(params);
return doGetSSLDown(url+"?"+queryString);
}

public static byte[] doGetSSLDown(String url){
CloseableHttpClient httpClient = createSSLClientDefault();
HttpGet httpGet = new HttpGet();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
byte[] by = null;
try {
httpGet.setURI(new URI(url));
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
by = inputSteam2Btye(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return by;
}

/***
* 拼接URL参数
* @param data
* @return
*/
public static String toQueryString(Map<?, ?> data) {
StringBuffer queryString = new StringBuffer();
for (Entry<?, ?> pair : data.entrySet()) {
queryString.append(pair.getKey() + "=");
queryString.append( pair.getValue() + "&");
}
if (queryString.length() > 0) {
queryString.deleteCharAt(queryString.length() - 1);
}
return queryString.toString();
}

/**
* URL编码
* @param source
* @param encode
* @return
*/
public static String urlEncode(String source, String encode) {
String result = source;
try {
result = URLEncoder.encode(source, encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}

/**
* 流转字节数组
* @param input
* @return
*/
public static byte[] inputSteam2Btye(InputStream input){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
IOUtils.copy(input, bos);
IOUtils.closeQuietly(input);
bos.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return bos.toByteArray();
}

public static String downloadImage(String imagepath,String savePath, String fileName){
URL url = null;
HttpURLConnection conn = null;
//获取连接
try {
url = new URL(imagepath);
if ("https".equals(url.getProtocol())) {
SSLContext context = null;
try {
context = SSLContext.getInstance("SSL", "SunJSSE");
context.init(new KeyManager[0], new TrustManager[] { new MyX509TrustManager() },
new java.security.SecureRandom());
} catch (Exception e) {
throw new IOException(e);
}
HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();
connHttps.setSSLSocketFactory(context.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
conn = connHttps;
} else {
conn = (HttpURLConnection) url.openConnection();
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
String contentType = conn.getContentType();
String suffix = ContentTypeConstant.getSuffix(contentType);
InputStream inputStream = conn.getInputStream();
FileOutputStream output = null;
//保存文件
if(suffix != null) {
String filePath = savePath+fileName + "."+suffix;
try {
// String fileName = savePath+suffix;
File file = new File(filePath);
output = new FileOutputStream(file);
int len = 0;
byte[] array = new byte[1024];
while ((len = inputStream.read(array)) != -1) {
output.write(array, 0, len);
}
output.flush();
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (output!=null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return filePath;
}else {
// 返回的不是图片类型
String result = "";
if(inputStream != null) {
result = IOUtils.toString(inputStream, CharEncoding.UTF_8);
}
logger.error("下载二维码失败原因:"+result);
}
} else {
logger.error(conn.getResponseCode() + "," + conn.getResponseMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

【参考】
Java HTTP 组件库选型

作者

光星

发布于

2018-01-22

更新于

2022-06-17

许可协议

评论