JAVA-HTTP 请求工具类

从别人那里拿来的对 HTTP 请求进行了封装的类,供参考和学习

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
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dianping.orderdish.dbhclient.common.RhinoConstants;
import com.dianping.orderdish.dbhclient.util.AuthUtil;
import com.dianping.orderdish.dbhclient.util.GzipUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.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.CookieStore;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.dianping.orderdish.dbh.web.entity.LoginConstants;
import com.dianping.orderdish.dbhclient.common.ClientInfoManager;
import com.dianping.orderdish.dbhclient.common.Constants;
import com.dianping.orderdish.dbhclient.config.HomeConfigManager;
import com.google.common.collect.ImmutableMap;

public class HttpService {
private static final Logger LOG = Logger.getLogger(HttpService.class);
/**
* 最大连接数320
*/
private static final int MAX_CONNECTION_NUM = 320;
/**
* 单路由最大连接数40
*/
private static final int MAX_PER_ROUTE = 40;
/**
* 连接池管理对象
*/
private PoolingHttpClientConnectionManager cm = null;

private HttpService() {
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
try {
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", socketFactory).register("http", new PlainConnectionSocketFactory()).build();
cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(MAX_CONNECTION_NUM);
cm.setDefaultMaxPerRoute(MAX_PER_ROUTE);
} catch (Exception e) {
LOG.error("init PoolingHttpClientConnectionManager Error" + e);
}
}

static class InstanceHolder {
static final HttpService instance = new HttpService();
}

public static HttpService getInstance() {
return InstanceHolder.instance;
}

private static String encode(String val, String charset) {
if (StringUtils.isNotBlank(val)) {
try {
return URLEncoder.encode(val, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
return val;
}

/**
* 创建线程安全的HttpClient
*
* @param config 客户端超时设置
*
* @return
*/
public CloseableHttpClient getHttpsClient(RequestConfig config, CookieStore cookieStore) {
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config)
.setDefaultCookieStore(cookieStore).setConnectionManager(this.cm).build();
return httpClient;
}

public String sendHttpGet(String url, List<Cookie> cookies, int connectTimeout, int socketTimeout)
throws ClientProtocolException, IOException {
CookieStore cookieStore = buildCookieStore(cookies);
CloseableHttpResponse response = null;
HttpGet httpGet = null;
try {

httpGet = new HttpGet(url);
//设置超时时间
// connectTimeout设置服务器请求超时时间
// socketTimeout设置服务器响应超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).build();
CloseableHttpClient client = getHttpsClient(requestConfig, cookieStore);

httpGet.setConfig(requestConfig);
injectHeader(httpGet);//注入ecom帐号
response = client.execute(httpGet);
String entity = EntityUtils.toString(response.getEntity());
LOG.info("sendHttpGet(). url=" + url + ", entity=" + entity + ", response=" + JSON.toJSONString(response));
return entity;
} catch (Exception e) {
if (e instanceof ConnectionPoolTimeoutException) {
//从连接池中取连接的超时时间
LOG.error("get connection time out from ConnectionManagerPool. " + e.getMessage());
} else if (e instanceof ConnectTimeoutException) {
// 通过网络与服务器建立连接的超时时间
LOG.error("server request time out. " + e.getMessage());
} else if (e instanceof SocketTimeoutException) {
// 服务器响应超时(已经请求了) ,Socket读数据的超时时间
LOG.error("server response time out. " + e.getMessage());
} else {
LOG.error("sendHttpGet exception. " + e.getMessage());
}
throw e;
} finally {
if (httpGet != null) {
httpGet.releaseConnection();
}
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (IOException e) {
LOG.error("sendHttpGet finally exception.", e);
}
}
}
}

public String sendHttpBAPost(String postUrl, String paramString, List<Cookie> cookies) throws IOException {
HttpPost httpPost = new HttpPost(postUrl);
AuthUtil.generateAuthAndDateHeader(httpPost, RhinoConstants.CLIENT_ID, RhinoConstants.SECRET);
StringEntity stringEntity = new StringEntity(paramString, Charset.forName("utf-8"));
stringEntity.setContentType("application/json");
return sendHttpPost(httpPost, stringEntity, cookies, 5000, 5000, true);
}

public String sendHttpPost(String postUrl, HttpEntity httpEntity, List<Cookie> cookies, int connectTimeout,
int socketTimeout, boolean log) throws ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(postUrl);
return sendHttpPost(httpPost, httpEntity, cookies, connectTimeout, socketTimeout, log);
}

public String sendHttpPost(HttpPost httpPost, HttpEntity httpEntity, List<Cookie> cookies, int connectTimeout,
int socketTimeout, boolean log) throws IOException {
CookieStore cookieStore = buildCookieStore(cookies);
//CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse response = null;
try {
//设置超时时间
// connectTimeout设置服务器请求超时时间
// socketTimeout设置服务器响应超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).build();
CloseableHttpClient client = getHttpsClient(requestConfig, cookieStore);
httpPost.setConfig(requestConfig);
httpPost.setEntity(httpEntity);
//injectHeader(httpPost);//注入ecom帐号
response = client.execute(httpPost);
String entity = EntityUtils.toString(response.getEntity());
if (log) {
if (org.apache.commons.lang.StringUtils.contains(entity, "mss.sankuai.com")) {
LOG.info("sendHttpPost(). url=" + httpPost.getURI() + ", params="
+ JSON.toJSONString(transfer2Map(httpEntity)) + ", response="
+ JSON.toJSONString(response));
} else {
LOG.info("sendHttpPost(). url=" + httpPost.getURI() + ", params="
+ JSON.toJSONString(transfer2Map(httpEntity)) + ", entity=" + entity + ", response="
+ JSON.toJSONString(response));
}
}
return entity;
} catch (Exception e) {
if (e instanceof ConnectionPoolTimeoutException) {
//从连接池中取连接的超时时间
LOG.error("get connection time out from ConnectionManagerPool. " + e.getMessage());
} else if (e instanceof ConnectTimeoutException) {
// 通过网络与服务器建立连接的超时时间
LOG.error("server request time out. " + e.getMessage());
} else if (e instanceof SocketTimeoutException) {
// 服务器响应超时(已经请求了) ,Socket读数据的超时时间
LOG.error("server response time out. " + e.getMessage());
} else {
LOG.error("sendHttpPost exception. " + e.getMessage());
}
throw e;
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (IOException e) {
LOG.error("sendHttpPost finally exception.", e);
}
}
}
}

private Map<String, String> transfer2Map(HttpEntity httpEntity) {
Map<String, String> map = new HashMap<String, String>();
try {
List<NameValuePair> lll = URLEncodedUtils.parse(httpEntity);
if (lll != null) {
for (NameValuePair pair : lll) {
map.put(pair.getName(), pair.getValue());
}
}
} catch (IOException e) {
LOG.error("transfer2Map error. ", e);
}
return map;
}

public BasicCookieStore buildCookieStore(List<Cookie> cookies) {
BasicCookieStore cookieStore = new BasicCookieStore();
cookies = cookies == null ? Collections.EMPTY_LIST : cookies;
for (Cookie cookie : cookies) {
cookieStore.addCookie(cookie);
}
return cookieStore;
}

public String sendHttpPost(String postUrl, Map<String, Object> params, List<Cookie> cookies)
throws ClientProtocolException, IOException {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(genPostParam(params), "UTF-8");
String result = sendHttpPost(postUrl, urlEncodedFormEntity, cookies, 5000, 5000, true);
return result;
}

public HttpResponse sendDownloadHttpPost(String postUrl, Map<String, Object> params, List<Cookie> cookies)
throws ClientProtocolException, IOException {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(genPostParam(params), "UTF-8");
return sendHttpPost(postUrl, urlEncodedFormEntity, cookies, 5000, 5000);
}

public String sendHttpPost(String postUrl, Map<String, Object> params) throws ClientProtocolException, IOException {
return this.sendHttpPost(postUrl, params, Collections.EMPTY_LIST);
}

public String sendStringEntityHttpPost(String postUrl, Map<String, Object> params, List<Cookie> cookies)
throws ClientProtocolException, IOException {
return sendStringEntityHttpPost(postUrl, JSON.toJSONString(params), cookies);
}

public String sendStringEntityHttpPost(String postUrl, String paramString) throws IOException {
StringEntity stringEntity = new StringEntity(paramString, Charset.forName("utf-8"));
stringEntity.setContentType("text/plain");
String result = sendHttpPost(postUrl, stringEntity, Collections.EMPTY_LIST, 5000, 5000, true);
return result;
}

public String sendGzipEntityHttpPost(String postUrl, String objectJson, List<Cookie> cookies)
throws ClientProtocolException, IOException {
// 设置超时时间
byte[] compressedBytes = GzipUtils.compress(objectJson);
LOG.info(postUrl + "请求压缩后数据大小:" + compressedBytes.length);
ByteArrayEntity entity = new ByteArrayEntity(compressedBytes, ContentType.TEXT_PLAIN);

return sendHttpPost(postUrl, entity, cookies, 5000, 30000, false);
}

/**
* 发送StringEntity类型的HttpPost
*
* @param postUrl
* @param paramString
* @param cookies
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String sendStringEntityHttpPost_noLog(String postUrl, String paramString, List<Cookie> cookies,
int socketTimeout) throws ClientProtocolException, IOException {
StringEntity stringEntity = new StringEntity(paramString, Charset.forName("utf-8"));
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("utf-8");
String result = sendHttpPost(postUrl, stringEntity, cookies, 5000, socketTimeout, false);
return result;
}

public String sendStringEntityHttpPost(String postUrl, String paramString, List<Cookie> cookies)
throws ClientProtocolException, IOException {
String result = sendStringEntityHttpPost_noLog(postUrl, paramString, cookies, 5000);
LOG.info("sendHttpPost(). url=" + postUrl + ", params=" + paramString + ", response=" + result);
return result;
}

public String sendHttpGet(String getUrl, List<Cookie> cookies) throws ClientProtocolException, IOException {
return this.sendHttpGet(getUrl, cookies, 5000, 5000);
}

public String sendHttpGet(String postUrl) throws IOException {
return this.sendHttpGet(postUrl, Collections.<Cookie>emptyList());
}

public List<Cookie> createCookies(String domain, String path, Map<String, String> keyValues) {
List<Cookie> result = new ArrayList<Cookie>();
if (MapUtils.isEmpty(keyValues)) {
return result;
}
for (Map.Entry<String, String> entry : keyValues.entrySet()) {
BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue());
cookie.setDomain(domain);
cookie.setPath(path);
result.add(cookie);
}
return result;
}

public List<Cookie> createLoginCookies() {
List<Cookie> result = new ArrayList<Cookie>();
String shopIdValue = String.valueOf(HomeConfigManager.getInstance().getShopId());
String token = HomeConfigManager.getInstance().getToken();
token = token == null ? StringUtils.EMPTY : token;
String bsid = HomeConfigManager.getInstance().getBSID();
bsid = bsid == null ? StringUtils.EMPTY : bsid;
result.addAll(this.createCookies(Constants.DATA_SERVER_BETA, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, "pc-token", token, "BSID", bsid)));
result.addAll(this.createCookies(Constants.DATA_SERVER, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, "pc-token", token, "BSID", bsid)));
return result;
}

public List<Cookie> createDownLoadCookies(String betaDomain, String domain, String bsidName) {
List<Cookie> result = new ArrayList<Cookie>();
String shopIdValue = String.valueOf(HomeConfigManager.getInstance().getShopId());
String bsid = HomeConfigManager.getInstance().getBSID();
bsid = bsid == null ? StringUtils.EMPTY : bsid;
// 线下
result.addAll(this.createCookies(betaDomain, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, bsidName, bsid)));
//线上
result.addAll(this.createCookies(domain, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, bsidName, bsid)));
return result;
}

private List<NameValuePair> genPostParam(Map<String, Object> params) {
if (params == null) {
return null;
}
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(),
entry.getValue() == null ? null : entry.getValue().toString()));
}
return formParams;
}

public List<Cookie> createUploadDataCookies() {
List<Cookie> result = new ArrayList<Cookie>();
String shopIdValue = String.valueOf(HomeConfigManager.getInstance().getShopId());
String token = HomeConfigManager.getInstance().getToken();
token = token == null ? StringUtils.EMPTY : token;
String bsid = HomeConfigManager.getInstance().getBSID();
bsid = bsid == null ? StringUtils.EMPTY : bsid;
result.addAll(this.createCookies(Constants.DATA_SERVER_BETA, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, "pc-token", token, "BSID", bsid)));
result.addAll(this.createCookies(Constants.DATA_SERVER, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, "pc-token", token, "BSID", bsid)));
return result;
}

public List<Cookie> createOrderCreationResultCookies() {
List<Cookie> result = new ArrayList<Cookie>();
String shopIdValue = String.valueOf(HomeConfigManager.getInstance().getShopId());
String token = HomeConfigManager.getInstance().getToken();
token = token == null ? StringUtils.EMPTY : token;
String bsid = HomeConfigManager.getInstance().getBSID();
bsid = bsid == null ? StringUtils.EMPTY : bsid;
result.addAll(this.createCookies(Constants.DATA_SERVER_BETA, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, "pc-token", token, "BSID", bsid)));
result.addAll(this.createCookies(Constants.DATA_SERVER, "/",
ImmutableMap.<String, String>of("shopId", shopIdValue, "pc-token", token, "BSID", bsid)));
return result;
}

private void injectHeader(HttpRequestBase request) {
String loginName = HomeConfigManager.getInstance().getProperty(LoginConstants.loginName);
if (StringUtils.isNotBlank(loginName)) {
request.addHeader(LoginConstants.loginName, loginName);
}
String clientVersion = ClientInfoManager.getInstance().getVersion();
request.addHeader(HomeConfigManager.KEY_CLIENT_VERSION, clientVersion);

String clientVersionId = HomeConfigManager.getInstance().getProperty(HomeConfigManager.KEY_CLIENT_VERSION_ID);
request.addHeader(HomeConfigManager.KEY_CLIENT_VERSION_ID, clientVersionId);

String posVersion = HomeConfigManager.getInstance().getProperty(HomeConfigManager.KEY_POS_VERSION);
request.addHeader(HomeConfigManager.KEY_POS_VERSION, encode(posVersion, "UTF-8"));
String posVersionId = HomeConfigManager.getInstance().getProperty(HomeConfigManager.KEY_POS_VERSION_ID);
request.addHeader(HomeConfigManager.KEY_POS_VERSION_ID, posVersionId);
String pluginVersion = HomeConfigManager.getInstance().getProperty(HomeConfigManager.KEY_PLUGIN_VERSION);
request.addHeader(HomeConfigManager.KEY_PLUGIN_VERSION, pluginVersion);
String pluginVersionId = HomeConfigManager.getInstance().getProperty(HomeConfigManager.KEY_PLUGIN_VERSION_ID);
request.addHeader(HomeConfigManager.KEY_PLUGIN_VERSION_ID, pluginVersionId);
}

public HttpResponse sendHttpPost(String postUrl, HttpEntity httpEntity, List<Cookie> cookies, int connectTimeout,
int socketTimeout) throws ClientProtocolException, IOException {
CookieStore cookieStore = buildCookieStore(cookies);
CloseableHttpResponse response = null;
HttpPost httpPost = null;
try {
httpPost = new HttpPost(postUrl);
//设置超时时间
// connectTimeout设置服务器请求超时时间
// socketTimeout设置服务器响应超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).build();
CloseableHttpClient client = getHttpsClient(requestConfig, cookieStore);
httpPost.setConfig(requestConfig);
httpPost.setEntity(httpEntity);
injectHeader(httpPost);//注入ecom帐号
response = client.execute(httpPost);
} catch (Exception e) {
LOG.error("sendHttpPost exception", e);
}
return response;
}

public HttpResponse sendDownloadHttpGet(String getUrl, List<Cookie> cookies)
throws ClientProtocolException, IOException {
return this.sendDownloadHttpGet(getUrl, cookies, 5000, 5000);
}

public HttpResponse sendDownloadHttpGet(String url, List<Cookie> cookies, int connectTimeout, int socketTimeout)
throws ClientProtocolException, IOException {
CookieStore cookieStore = buildCookieStore(cookies);
CloseableHttpResponse response = null;
HttpGet httpGet = null;
try {
//Http get
httpGet = new HttpGet(url);
//设置超时时间
// connectTimeout设置服务器请求超时时间
// socketTimeout设置服务器响应超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).build();
CloseableHttpClient client = getHttpsClient(requestConfig, cookieStore);

httpGet.setConfig(requestConfig);
injectHeader(httpGet);//注入ecom帐号
response = client.execute(httpGet);

} catch (Exception e) {
LOG.error("sendDownloadHttpGet exception", e);
}

return response;
}
}
分享