1.RestTemplate的配置
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
2.发送get请求
.getForEntity
返回结果里包含http header、状态信息等参数,可以通过body获取需要结果
.getForObject
直接返回body结果
3.发送post请求
也是通过getForEntity、getForObject调用
restTemplate.postForEntity(“http://localhost:8888/rest/echo“, map, String.class);
第二个参数是body内容,如果需要以form表单格式提交,需要设置header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("body", "我是一个body");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8888/rest/echo", request, String.class);
System.out.println(responseEntity.getBody());
4.restTemplate超时时间设置
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(10000)
.setReadTimeout(10000)
.build();
}
5.简单重试
for (int i = 1; i <= count; i++) {
try {
System.out.println("try:"+i);
restTemplate.postForEntity("http://localhost:8888/rest/echo", request, String.class);
break;
} catch (Exception e) {
e.printStackTrace();
try {
Thread.sleep(100 * i);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}