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
| @Configuration public class RestTemplateConfig {
@Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(5000); factory.setConnectTimeout(15000);
return factory; }
@Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate; }
}
|
也可以通过RestTemplateBuilder来设置一些参数,比如验证、超时时间等。
使用
1 2 3 4
| HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> requestEntity = new HttpEntity<String>(jsonString, requestHeaders); ResponseEntity<String> res = restTemplate.postForEntity(url, requestEntity, String.class);
|