SpringBoot使用RestTemplate做Http请求

前言

基本的网络请求

使用

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-05-27
*/
@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}

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
@Slf4j
@Configuration
public class RestConfig {

@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(3))
.setReadTimeout(Duration.ofSeconds(10)).build();
restTemplate.setRequestFactory(factory);
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
return restTemplate;
}

@Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
try {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
httpClientBuilder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
poolingHttpClientConnectionManager.setMaxTotal(2700);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);
httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
HttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient);
clientHttpRequestFactory.setConnectTimeout(20000);
clientHttpRequestFactory.setReadTimeout(30000);
clientHttpRequestFactory.setConnectionRequestTimeout(20000);
return clientHttpRequestFactory;
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("===> init http client pool error!!!", e);
}
return null;
}

}

测试

随便创建一个对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-05-27
*/
@Data
public class User {

private String username;
private String password;

// 注意需要无参构造方法
public User() {
}

public User(String username, String password) {
this.username = username;
this.password = password;
}
}

自己提供2个接口供 RestTemplate 测试

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
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-05-27
*/
@RestController
@RequestMapping
public class TestController {

// http://localhost:8888/user
@GetMapping("/user")
public User getUser() {
return new User("admin", "123");
}

// http://localhost:8888/user/1?name=admin&age=17
@GetMapping("/user/{id}")
public Object getInfo(@PathVariable("id") Integer id, @RequestParam String name, @RequestParam Integer age) {
return "id=" + id + ";name=" + name + ";age=" + age;
}

// http://localhost:8888/save
@PostMapping("/save")
public User save(@RequestBody User user, HttpServletRequest request) {
user.setPassword(request.getHeader("Authorization"));
return user;
}

// http://localhost:8888/list
@GetMapping("/list")
public List<User> list() {
return Arrays.asList(new User("admin", "456"));
}
}

单元测试

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
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-05-27
*/
@SpringBootTest
class TestControllerTest {

@Autowired
RestTemplate restTemplate;

/**
* User(username=admin, password=123)
*/
@Test
void getForEntity() {
ResponseEntity<User> response = restTemplate.getForEntity("http://localhost:8888/user", User.class);
User body = response.getBody();
System.out.println(body);
}

/**
* User(username=admin, password=123)
*/
@Test
void getForObject() {
User user = restTemplate.getForObject("http://localhost:8888/user", User.class);
System.out.println(user);
}

/**
* User(username=admin, password=123)
*/
@Test
void exchange() {

HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity httpEntity = new HttpEntity(null, httpHeaders);
ResponseEntity<User> exchange = restTemplate.exchange("http://localhost:8888/user", HttpMethod.GET, httpEntity, User.class);
User body = exchange.getBody();
System.out.println(body);
}

/**
* id=1;name=当我遇上你;age=17
*/
@Test
void getForEntityByParams() {
Map<String, Object> params = new HashMap<>();
params.put("name", "当我遇上你");
params.put("age", 17);
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8888/user/1?name={name}&age={age}", String.class, params);
System.out.println(responseEntity.getBody());
}

/**
* id=1;name=当我遇上你;age=17
*/
@Test
void getForObjectByParams() {
Map<String, Object> params = new HashMap<>();
params.put("id", 1);
params.put("name", "当我遇上你");
params.put("age", 17);
String res = restTemplate.getForObject("http://localhost:8888/user/{id}?name={name}&age={age}", String.class, params);
System.out.println(res);
}

/**
* id=1;name=当我遇上你;age=17
*/
@Test
void getExchangeByParams() {

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity httpEntity = new HttpEntity(headers);

Map<String, Object> params = new HashMap<>();
params.put("id", 1);
params.put("name", "当我遇上你");
params.put("age", 17);

ResponseEntity<String> exchange = restTemplate.exchange("http://localhost:8888/user/{id}?name={name}&age={age}", HttpMethod.GET, httpEntity, String.class, params);
System.out.println(exchange.getBody());
}

/**
* id=1;name=当我遇上你;age=17
*/
@Test
void getExchangeByUriComponentsBuilder() {

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity httpEntity = new HttpEntity(headers);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8888/user/1")
.queryParam("name", "当我遇上你")
.queryParam("age", 17);

ResponseEntity<String> exchange = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, httpEntity, String.class);
System.out.println(exchange.getBody());
}

/**
* User(username=当我遇上你, password=777)
*/
@Test
void postForObject() {

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "777");
headers.setContentType(MediaType.APPLICATION_JSON);
User body = new User("当我遇上你", "123");
HttpEntity<User> request = new HttpEntity<>(body, headers);
User user = restTemplate.postForObject("http://localhost:8888/save", request, User.class);
System.out.println(user);
}

/**
* [User(username=admin, password=456)]
*/
@Test
void list1() {
User[] users = restTemplate.getForObject("http://localhost:8888/list", User[].class);
List<User> list = Arrays.asList(users);
System.out.println(list);
}

/**
* [User(username=admin, password=456)]
*/
@Test
void list2() {
ResponseEntity<List<User>> responseEntity = restTemplate.exchange("http://localhost:8888/list", HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>(){});
List<User> body = responseEntity.getBody();
System.out.println(body);
}
}

总结

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】支持。