RestTemplate 使用

主要配置

  • 连接池
  • 支持 IP 形式的 HTTPS 请求

ReqParams.java

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
import lombok.Getter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Getter
public class ReqParams implements Serializable {
private static final long serialVersionUID = 7009345055076298012L;

private final Map<String, List<String>> params;

ReqParams(Map<String, List<String>> params) {
this.params = params;
}

public boolean isEmpty() {
return this.params.isEmpty();
}

public Set<Map.Entry<String, List<String>>> entrySet() {
return this.params.entrySet();
}

public static class Builder {
private final Map<String, List<String>> params;

public Builder() {
this.params = new HashMap<>(4);
}

public Builder put(String name, List<String> value) {
params.put(name, value);
return this;
}

public Builder put(String name, String value) {
params.put(name, Collections.singletonList(value));
return this;
}

public Builder add(String name, String value) {
List<String> list = params.get(name);
if (list == null) {
list = new ArrayList<>();
}
list.add(value);
params.put(name, list);
return this;
}

public ReqParams build() {
return new ReqParams(params);
}
}
}

ReqHeaders.java

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
import lombok.Getter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Getter
public class ReqHeaders implements Serializable {
private static final long serialVersionUID = -7187023781009842386L;

private final Map<String, List<String>> headers;

ReqHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}

public boolean isEmpty() {
return this.headers.isEmpty();
}

public Set<Map.Entry<String, List<String>>> entrySet() {
return this.headers.entrySet();
}

public static class Builder {
private final Map<String, List<String>> headers;

public Builder() {
this.headers = new HashMap<>(4);
}

public Builder put(String name, List<String> value) {
headers.put(name, value);
return this;
}

public Builder put(String name, String value) {
headers.put(name, Collections.singletonList(value));
return this;
}

public Builder add(String name, String value) {
List<String> list = headers.get(name);
if (list == null) {
list = new ArrayList<>();
}
list.add(value);
headers.put(name, list);
return this;
}

public ReqHeaders build() {
return new ReqHeaders(headers);
}
}
}

RestTemplateUtils

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
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author yl
*/
@Slf4j
public final class RestTemplateUtils {
/**
* 从连接池获取连接的超时时间,单位:ms
*/
private static final int CONNECTION_REQUEST_TIMEOUT = 5 * 1000;
/**
* 与接口服务器连接超时时间,单位:ms
*/
private static final int CONNECT_TIMEOUT = 10 * 1000;
/**
* 获取响应数据超时时间,单位:ms
*/
private static final int SOCKET_TIMEOUT = 30 * 1000;

private static final int MAX_CONN_TOTAL = 100;
private static final int MAX_CONN_PER_ROUTE = 10;
/**
* 单位:ms
*/
private static final int CONNECTION_TIME_TO_LIVE = 60 * 1000;
private static final RestTemplate REST_TEMPLATE;

static {
RequestConfig.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 = HttpClientBuilder.create().useSystemProperties();
// 禁用重试
clientBuilder.disableAutomaticRetries();
clientBuilder.setDefaultRequestConfig(defaultRequestConfig);
clientBuilder.setMaxConnTotal(MAX_CONN_TOTAL);
clientBuilder.setMaxConnPerRoute(MAX_CONN_PER_ROUTE);
clientBuilder.setConnectionTimeToLive(CONNECTION_TIME_TO_LIVE, TimeUnit.MILLISECONDS);
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 (Exception e) {
log.error("SSLSocketFactory 初始化 ---> msg: {}", e.getMessage(), e);
}
CloseableHttpClient httpClient = clientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
REST_TEMPLATE = new RestTemplate(factory);
}

/**
* 发送 GET 请求
*
* @param platform 接口平台名称
* @param url 接口地址
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> get(String platform, String url, Class<T> responseType) {
return get(platform, url, null, null, responseType);
}

/**
* 发送 GET 请求
*
* @param platform 接口平台名称
* @param url 接口地址
* @param params 请求参数
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> get(String platform, String url, ReqParams params, Class<T> responseType) {
return get(platform, url, params, null, responseType);
}

/**
* 发送 GET 请求
*
* @param platform 接口平台名称
* @param url 接口地址
* @param headers 请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> get(String platform, String url, ReqHeaders headers, Class<T> responseType) {
return get(platform, url, null, headers, responseType);
}

/**
* 发送 GET 请求
*
* @param platform 接口平台名称
* @param url 接口地址
* @param params 请求参数
* @param headers 请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> get(String platform, String url, ReqParams params, ReqHeaders headers, Class<T> responseType) {
boolean contain = url.contains("?");
if (params != null && !params.isEmpty()) {
StringBuilder sb = new StringBuilder(url);
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
List<String> list = entry.getValue();
String value = "";
if (!CollectionUtils.isEmpty(list)) {
value = String.join(",", list);
}
if (contain) {
sb.append("&").append(key).append("=").append(value);
} else {
sb.append("?").append(key).append("=").append(value);
contain = true;
}
}
url = sb.toString();
}
HttpEntity<String> requestEntity = null;
if (headers != null && !headers.isEmpty()) {
HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
List<String> list = entry.getValue();
httpHeaders.addAll(key, list);
}
requestEntity = new HttpEntity<>(httpHeaders);
}
return exchange(platform, HttpMethod.GET, url, requestEntity, responseType);
}

/**
* 发送 POST 表单请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, Class<T> responseType) {
return post(platform, url, (ReqParams) null, (ReqHeaders) null, responseType);
}

/**
* 发送 POST 表单请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param params 请求参数
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, ReqParams params, Class<T> responseType) {
return post(platform, url, params, (ReqHeaders) null, responseType);
}

/**
* 发送 POST 表单请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param headers 请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, ReqHeaders headers, Class<T> responseType) {
return post(platform, url, (ReqParams) null, headers, responseType);
}

/**
* 发送 POST 表单请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, ReqParams params, ReqHeaders headers, Class<T> responseType) {
// 封装参数,不要替换为 Map 与 HashMap,否则参数无法传递
MultiValueMap<String, String> multiValueMap = null;
if (params != null && !params.isEmpty()) {
multiValueMap = new LinkedMultiValueMap<>();
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
List<String> list = entry.getValue();
multiValueMap.put(key, list);
}
}
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
List<String> list = entry.getValue();
httpHeaders.addAll(key, list);
}
}
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity;
if (multiValueMap == null || multiValueMap.isEmpty()) {
requestEntity = new HttpEntity<>(httpHeaders);
} else {
requestEntity = new HttpEntity<>(multiValueMap, httpHeaders);
}
return exchange(platform, HttpMethod.POST, url, requestEntity, responseType);
}

/**
* 发送 POST Payload 请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param payload 请求 body 体,一般为 json 格式
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, String payload, Class<T> responseType) {
return post(platform, url, payload, null, null, responseType);
}

/**
* 发送 POST Payload 请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param payload 请求 body 体,一般为 json 格式
* @param params 请求参数
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, String payload, ReqParams params, Class<T> responseType) {
return post(platform, url, payload, params, null, responseType);
}

/**
* 发送 POST Payload 请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param payload 请求 body 体,一般为 json 格式
* @param headers 请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, String payload, ReqHeaders headers, Class<T> responseType) {
return post(platform, url, payload, null, headers, responseType);
}

/**
* 发送 POST Payload 请求
*
* @param platform 接口平台名称
* @param url 请求地址
* @param payload 请求 body 体,一般为 json 格式
* @param params 请求参数
* @param headers 请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @return 返回数据
*/
public static <T> Rs<T> post(String platform, String url, String payload,
ReqParams params, ReqHeaders headers, Class<T> responseType) {
Assert.hasText(payload, "payload 不能为空");
boolean contain = url.contains("?");
if (params != null && !params.isEmpty()) {
StringBuilder sb = new StringBuilder(url);
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
List<String> list = entry.getValue();
String value = "";
if (!CollectionUtils.isEmpty(list)) {
value = String.join(",", list);
}
if (contain) {
sb.append("&").append(key).append("=").append(value);
} else {
sb.append("?").append(key).append("=").append(value);
contain = true;
}
}
url = sb.toString();
}
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
List<String> list = entry.getValue();
httpHeaders.addAll(key, list);
}
}
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(payload, httpHeaders);
return exchange(platform, HttpMethod.POST, url, requestEntity, responseType);
}

/**
* 发送请求
*
* @param platform 接口平台名称
* @param method 请求方式
* @param url 请求地址
* @param requestEntity 请求参数和请求头
* @param responseType 返回类型:一般传入 String.class、byte[].class
* @param uriVariables 请求地址的格式化参数<br/>
* &emsp;// 在地址中加入格式化参数 id<br/>
* &emsp;String url = "http://localhost:8080/api/v1/user/{id}";<br/>
* &emsp;// 准备格式化参数<br/>
* &emsp;Map<String, String> uriVariables = Maps.newHashMap();<br/>
* &emsp;uriVariables.put("id", "111");
* @return 返回数据
*/
public static <T> Rs<T> exchange(String platform, HttpMethod method, String url, HttpEntity<?> requestEntity,
Class<T> responseType, Object... uriVariables) {
Assert.hasText(url, "请求 url 不能为空");
Assert.notNull(method, "请求 method 不能为空");
Assert.notNull(responseType, "返回类型 responseType 不能为空");
platform = StringUtils.hasText(platform) ? platform : "接口";
HttpHeaders headers = null;
boolean hasHeaders = false;
Object body = null;
if (requestEntity != null) {
headers = requestEntity.getHeaders();
hasHeaders = !headers.isEmpty();
body = requestEntity.getBody();
}
String str = "";
String msg;
Exception ex;
long beginTime = System.currentTimeMillis();
try {
ResponseEntity<T> response =
REST_TEMPLATE.exchange(url, method, requestEntity, responseType, uriVariables);
long cost = System.currentTimeMillis() - beginTime;
T result = response.getBody();
if (result instanceof byte[]) {
HttpHeaders httpHeaders = response.getHeaders();
if (!httpHeaders.isEmpty()) {
MediaType mediaType = httpHeaders.getContentType();
if (mediaType != null) {
String type = mediaType.getType();
String subtype = mediaType.getSubtype();
if (MediaType.IMAGE_PNG.getType().equalsIgnoreCase(type)
|| MediaType.APPLICATION_PDF.getSubtype().equalsIgnoreCase(subtype)
|| MediaType.APPLICATION_OCTET_STREAM.getSubtype().equalsIgnoreCase(subtype)) {
str = "文件流数据 " + mediaType;
} else {
Charset charset = getContentTypeCharset(mediaType);
str = new String((byte[]) result, charset);
}
}
}
} else if (result instanceof String) {
str = (String) result;
} else {
if (result != null) {
str = result.toString();
}
}
HttpStatus statusCode = response.getStatusCode();
if (hasHeaders) {
log.info("{}:{} {} {}, 耗时: {}, 头部: {}, 请求: {}, 返回: {}", platform, method, statusCode.value(), url,
cost, headers, body, replaceLineSeparator(str));
} else {
log.info("{}:{} {} {}, 耗时: {}, 请求: {}, 返回: {}", platform, method, statusCode.value(), url,
cost, body, replaceLineSeparator(str));
}
if (HttpStatus.OK.equals(statusCode)) {
return Rs.okMsg(getCause(statusCode), result);
}
return Rs.ok(result);
} catch (RestClientException e) {
ex = e;
msg = "调用接口异常";
}
if (hasHeaders) {
log.error("{}:{} {}, 头部: {}, 请求: {}, 返回: {}, 异常: {}", platform, method, url,
headers, body, replaceLineSeparator(str), msg, ex);
} else {
log.error("{}:{} {}, 请求: {}, 返回: {}, 异常: {}", platform, method, url,
body, replaceLineSeparator(str), msg, ex);
}
return Rs.error(msg);
}

private static final MediaType APPLICATION_PLUS_JSON = new MediaType("application", "*+json");

/**
* 参考 {@link org.springframework.http.converter.StringHttpMessageConverter} 的 getContentTypeCharset(MediaType)
*/
private static Charset getContentTypeCharset(@Nullable MediaType contentType) {
if (contentType != null) {
Charset charset = contentType.getCharset();
if (charset != null) {
return charset;
} else if (contentType.isCompatibleWith(MediaType.APPLICATION_JSON) ||
contentType.isCompatibleWith(APPLICATION_PLUS_JSON)) {
// Matching to AbstractJackson2HttpMessageConverter#DEFAULT_CHARSET
return StandardCharsets.UTF_8;
}
}
return StandardCharsets.ISO_8859_1;
}

/**
* 通过statusCode获取错误信息
*/
private static String getCause(HttpStatus statusCode) {
String cause = "";
switch (statusCode) {
case OK:
break;
case BAD_REQUEST:
cause = "请求出错";
break;
case UNAUTHORIZED:
cause = "未授权";
break;
case FORBIDDEN:
cause = "拒绝访问";
break;
case NOT_FOUND:
cause = "请求的URI是无效的或者所请求的资源不存在";
break;
case NOT_ACCEPTABLE:
cause = "不接受请求";
break;
case INTERNAL_SERVER_ERROR:
cause = "内部服务器错误";
break;
case BAD_GATEWAY:
cause = "错误的网关";
break;
case SERVICE_UNAVAILABLE:
cause = "暂停服务";
break;
default:
cause = "其他错误";
}
return statusCode + ":" + cause;
}

private static String replaceLineSeparator(String str) {
return StringUtils.hasText(str) ?
str.replaceAll("\\n", "")
.replaceAll("\\r", "") : str;
}
}
  • 本文作者: forever杨
  • 本文链接: https://blog.yl-online.top/posts/e98e5e02.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。如果文章内容对你有用,请记录到你的笔记中。本博客站点随时会停止服务,请不要收藏、转载!