首页 归档 关于 文件 Github
×

SpringBoot配置RestTemplate

2020-06-23 11:07:40
SpringBoot
  • RestTemplate
本文总阅读量(次):
本文字数统计(字):899
本文阅读时长(分):5

以下为2种配置方式,均可实现实现远程调用,jar引入只要其一即可;

方式一:RestTemplate + HttpClients

方式二:RestTemplate + OkHttp3

依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>>2.4.0</version>
<relativePath/>
</parent>

<dependency>
<!-- 不需要版本号 -->
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>

配置

RestTemplate + HttpClients

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
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
/**
* className RestTemplateConfig
* author demon
* createTime 2021/6/8 13:09
* description RestTemplate + HttpClients 实现远程调用
*/
@Configuration
class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
//使用httpclient的factory
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
// 请求连接超时时间 毫秒
requestFactory.setConnectTimeout(1000 * 60);
// 从链接池获取连接超时时间 毫秒
requestFactory.setConnectionRequestTimeout(6000);
// 获取数据超时时间 毫秒
requestFactory.setReadTimeout(1000 * 360);
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
}

RestTemplate + OkHttp3

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

import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
* className RestTemplateConfig
* author demon
* createTime 2021/6/8 13:09
* description RestTemplate + OkHttp3 实现远程调用
*/
@Slf4j
@Component
public class RestTemplateConfig {

/**
* 基于OkHttp3配置RestTemplate
*/
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
RestTemplate restTemplate = restTemplateBuilder
.errorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return clientHttpResponse.getStatusCode().value() != 200 && clientHttpResponse.getStatusCode().value() != 302;
}

@Override
public void handleError(ClientHttpResponse clientHttpResponse) {

}

@Override
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
log.error("=======================ERROR============================");
log.error("DateTime:{}", LocalDateTime.ofInstant(Instant.ofEpochMilli(response.getHeaders().getDate()), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
log.error("HOST:{},URI:{}", url.getHost(), url.getPath());
log.error("Method:{}", method.name());
log.error("Exception:{}", response.getStatusCode());
log.error("========================================================");
}
})
.interceptors((ClientHttpRequestInterceptor) (httpRequest, bytes, clientHttpRequestExecution) -> {
HttpHeaders headers = httpRequest.getHeaders();
// 加入自定义字段
headers.add("Content-Type", "application/json;charset=UTF-8");
return clientHttpRequestExecution.execute(httpRequest, bytes);
})
.build();
restTemplate.setRequestFactory(new OkHttp3ClientHttpRequestFactory(new OkHttpClient.Builder()
// 整个流程耗费的超时时间
.callTimeout(180, TimeUnit.SECONDS)
// 读取耗时
.readTimeout(60, TimeUnit.SECONDS)
// 写入耗时
.writeTimeout(60, TimeUnit.SECONDS)
// 三次握手 + SSL建立耗时
.connectTimeout(60, TimeUnit.SECONDS)
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
// 当连接失败,尝试重连
.retryOnConnectionFailure(true)
// 最大空闲连接数及连接的保活时间进行配置
.connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES))
// 绕过需要SSL证书验证的HTTPS的请求
.hostnameVerifier((s, sslSession) -> true)
.build()));
return restTemplate;
}

@Bean
public SSLSocketFactory sslSocketFactory() {
try {
// 信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}

@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}

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

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}


}

测试

1
2
3
4
5
6
7
8
9
10
11
12
@Slf4j
@SpringBootTest
class SpringBootApiApplicationTests {
@Resource
private RestTemplate restTemplate;
@Test
void contextLoads(){
String url = "https://www.baidu.com/";
String resp = restTemplate.getForObject(url, String.class);
System.out.println(resp);
}
}

结果

20200623115758

RestTemplate简单使用
RestTemplate封装使用

完
发布Java程序为Windows服务 (含有Java环境)一
RabbitMq:使用交换机topic+routingKey的模式 - 优先级 (spring-boot)

本文标题:SpringBoot配置RestTemplate

文章作者:十二

发布时间:2020-06-23 11:07:40

最后更新:2022-08-16 16:11:51

原始链接:https://www.zhuqiaolun.com/2020/06/1592881660483/1592881660483/

许可协议:署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

头像

十二

我想起那天夕阳下的奔跑,那是我逝去的青春。

分类

  • Blog4
  • ElasticSearch13
  • Git2
  • Go-FastDfs2
  • IDEA2
  • J-Package6
  • J-Tools21
  • Java2
  • JavaFx6
  • Kafka4
  • Linux2
  • Logger6
  • Maven5
  • MyBatis6
  • MyCat3
  • MySql2
  • Nginx5
  • OceanBase1
  • RabbitMq4
  • Redis6
  • SVN1
  • SpringBoot16
  • Tomcat6
  • WebService2
  • Windows2
  • kubernetes10

归档

  • 一月 20261
  • 十二月 20253
  • 八月 20252
  • 六月 20251
  • 二月 20251
  • 十二月 20244
  • 八月 202416
  • 六月 20241
  • 九月 20231
  • 八月 20231
  • 七月 20232
  • 八月 20222
  • 三月 202214
  • 二月 20224
  • 十一月 20211
  • 七月 20215
  • 六月 20213
  • 五月 20213
  • 四月 20211
  • 三月 202116
  • 二月 20212
  • 一月 20211
  • 十一月 202014
  • 十月 20201
  • 九月 202014
  • 八月 20205
  • 七月 20204
  • 六月 20208
  • 五月 20208

作品

我的微信 我的文件

网站信息

本站运行时间统计: 载入中...
本站文章字数统计:103.2k
本站文章数量统计:139
© 2026 十二  |  鄂ICP备18019781号-1  |  鄂公网安备42118202000044号
驱动于 Hexo  | 主题 antiquity  |  不蒜子告之 阁下是第个访客
首页 归档 关于 文件 Github