httpclient 使用

主要配置

  • 连接池
  • 支持 IP 形式的 HTTPS 请求
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
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
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.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;

@Slf4j
public enum HttpsUtils {
/**
* gbk 编码
*/
gbk {
@Override
public String getCharset() {
return "GBK";
}
},
utf8 {
@Override
public String getCharset() {
return "UTF-8";
}
};

/**
* 获取编码
*/
public String getCharset() {
throw new AbstractMethodError();
}

/**
* 从连接池获取连接的超时时间
*/
private static final int CONNECTION_REQUEST_TIMEOUT = 5 * 1000;
/**
* 与接口服务器连接超时时间
*/
private static final int CONNECT_TIMEOUT = 10 * 1000;
/**
* 获取响应数据超时时间
*/
private static final int SOCKET_TIMEOUT = 30 * 1000;

private static final int MAX_CONN_TOTAL = 500;
private static final int MAX_CONN_PER_ROUTE = 100;
private static final CloseableHttpClient HTTP_CLIENT;
private String logName = "接口";

static {
Builder builder = RequestConfig.custom();
builder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
RequestConfig defaultRequestConfig = builder.build();
/*
* 4.3以上版本推荐使用HttpClientBuilder来创建client
*
* <pre>
* 1、HttpClientBuilder.setRetryHandler(HttpRequestRetryHandler retryHandler);请求重试处理。
* 2、HttpClientBuilder.setRedirectStrategy(RedirectStrategy redirectStrategy);设置重定向。
* 3、httpClientBuilder.setDefaultCookieStore(BasicCookieStore cookieStore);设置cookie store
* 4、HttpClientBuilder.setProxy(HttpHost proxy);设置代理服务器。
* 5、HttpClientBuilder.setDefaultRequestConfig(RequestConfig config);在此亦可设置RequestConfig。
* 6、HttpClientBuilder.setUserAgent(String userAgent);设置用户代理。
* </pre>
*/
HttpClientBuilder clientBuilder = HttpClients.custom();
// 禁用重试
clientBuilder.disableAutomaticRetries();
clientBuilder.setDefaultRequestConfig(defaultRequestConfig);
clientBuilder.setMaxConnTotal(MAX_CONN_TOTAL);
clientBuilder.setMaxConnPerRoute(MAX_CONN_PER_ROUTE);
try {
// SSL、TLS
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null,
new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}

@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}},
new java.security.SecureRandom()
);
clientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE));
} catch (NoSuchAlgorithmException | KeyManagementException e) {
log.error("RestTemplate 初始化 ---> msg: {}", e.getMessage(), e);
}
HTTP_CLIENT = clientBuilder.build();
}

public CloseableHttpClient getHttpClient() {
return HTTP_CLIENT;
}

public HttpsUtils setLogName(String logName) {
this.logName = logName;
return this;
}

/**
* 发送get请求
*/
public Rs<String> get(String url) {
HttpGet httpGet = new HttpGet(url);
return get(httpGet);
}

public Rs<String> get(HttpGet httpGet) {
String url = httpGet.getURI().toString();
Header[] allHeaders = httpGet.getAllHeaders();
String result = "";
String msg;
Exception ex;
try (CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet)) {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, this.getCharset());
}
log.info("{}:GET {} {}, 头部: {}, 返回: {}", logName, statusCode, url, Arrays.toString(allHeaders),
StringUtils.isBlank(result) ? result :
result.replaceAll("\\n", "")
.replaceAll("\\r", "")
);
if (statusCode != HttpStatus.SC_OK) {
return Rs.okMsg(getCause(statusCode), result);
}
return Rs.ok(result);
} catch (UnsupportedEncodingException e) {
ex = e;
msg = "不支持的字符编码";
} catch (ClientProtocolException e) {
ex = e;
msg = "HTTP协议错误";
} catch (SSLHandshakeException e) {
ex = e;
msg = "SSLHandshake 异常";
} catch (IOException e) {
ex = e;
msg = "socket超时,或者被重置";
if (e instanceof UnknownHostException) {
msg = "网络问题 unknown host";
} else if (e instanceof SSLPeerUnverifiedException) {
msg = "SSL 证书不匹配";
}
}
log.error("{}:GET {}, 头部: {}, 返回: {}, 异常: {}", logName, url, Arrays.toString(allHeaders),
StringUtils.isBlank(result) ? result :
result.replaceAll("\\n", "")
.replaceAll("\\r", ""),
msg, ex
);
return Rs.error(msg);
}

/**
* 发送post请求
*
* @param url 地址
*/
public Rs<String> post(String url) {
HttpPost httpPost = new HttpPost(url);
return post(httpPost);
}

/**
* 发送post请求:使用UrlEncodedFormEntity模拟表单提交
*
* @param url 地址
* @param nvpList 传值示例:<br/>
* List&lt;NameValuePair> nvpList = new ArrayList
* &lt;NameValuePair>();<br/>
* nvpList.add(new BasicNameValuePair("key", value));
*/
public Rs<String> post(String url, List<NameValuePair> nvpList) {
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvpList, this.getCharset()));
} catch (UnsupportedEncodingException e) {
return Rs.error("不支持的字符编码");
}
return post(httpPost);
}

/**
* 发送post请求:使用StringEntity提交application/json格式
*
* @param url 链接
* @param text json格式数据
*/
public Rs<String> post(String url, String text) {
return post(url, text, ContentType.create("application/json", this.getCharset()));
}

/**
* 发送post请求,自定义content-type类型
*
* @param url 链接
* @param text 数据
* @param contentType content-type类型
*/
public Rs<String> post(String url, String text, ContentType contentType) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(text, contentType));
return post(httpPost);
}

/**
* 发送post请求
*/
public Rs<String> post(HttpPost httpPost) {
String url = httpPost.getURI().toString();
Header[] allHeaders = httpPost.getAllHeaders();
String data = "";
try {
HttpEntity reqEntity = httpPost.getEntity();
if (reqEntity != null) {
data = EntityUtils.toString(reqEntity, this.getCharset());
}
} catch (IOException e) {
// ignore
}
String result = "";
String msg;
Exception ex;
try (CloseableHttpResponse response = HTTP_CLIENT.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, this.getCharset());
}
log.info("{}:POST {} {}, 头部: {}, 请求: {}, 返回: {}", logName, statusCode, url, Arrays.toString(allHeaders),
StringUtils.isBlank(data) ? data :
data.replaceAll("\\n", "")
.replaceAll("\\r", ""),
StringUtils.isBlank(result) ? result :
result.replaceAll("\\n", "")
.replaceAll("\\r", "")
);
if (statusCode != HttpStatus.SC_OK) {
return Rs.okMsg(getCause(statusCode), result);
}
return Rs.ok(result);
} catch (UnsupportedEncodingException e) {
msg = "不支持的字符编码";
ex = e;
} catch (ClientProtocolException e) {
msg = "HTTP协议错误";
ex = e;
} catch (SSLHandshakeException e) {
ex = e;
msg = "SSLHandshake 异常";
} catch (IOException e) {
ex = e;
msg = "socket超时,或者被重置";
if (e instanceof UnknownHostException) {
msg = "网络问题 unknown host";
} else if (e instanceof SSLPeerUnverifiedException) {
msg = "SSL 证书不匹配";
}
}
log.error("{}:POST {}, 头部: {}, 请求: {}, 返回: {}, 异常: {}", logName, url, Arrays.toString(allHeaders),
StringUtils.isBlank(data) ? data :
data.replaceAll("\\n", "")
.replaceAll("\\r", ""),
StringUtils.isBlank(result) ? result :
result.replaceAll("\\n", "")
.replaceAll("\\r", ""),
msg, ex
);
return Rs.error(msg);
}

/**
* 通过statusCode获取错误信息
*/
private static String getCause(int statusCode) {
String cause = "";
switch (statusCode) {
case HttpStatus.SC_NOT_MODIFIED:
break;
case HttpStatus.SC_BAD_REQUEST:
cause = "请求出错";
break;
case HttpStatus.SC_UNAUTHORIZED:
cause = "未授权";
break;
case HttpStatus.SC_FORBIDDEN:
cause = "拒绝访问";
break;
case HttpStatus.SC_NOT_FOUND:
cause = "请求的URI是无效的或者所请求的资源不存在";
break;
case HttpStatus.SC_NOT_ACCEPTABLE:
cause = "不接受请求";
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
cause = "内部服务器错误";
break;
case HttpStatus.SC_BAD_GATEWAY:
cause = "错误的网关";
break;
case HttpStatus.SC_SERVICE_UNAVAILABLE:
cause = "暂停服务";
break;
default:
cause = "其他错误";
}
return statusCode + ":" + cause;
}
}
  • 本文作者: forever杨
  • 本文链接: https://blog.yl-online.top/posts/812c7f75.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。如果文章内容对你有用,请记录到你的笔记中。本博客站点随时会停止服务,请不要收藏、转载!