getForObject
getForObject指get请求,并返回一个Object对象。这里有2个方法参数
- 第1个参数:请求的url地址
- 第2个参数:返回的结果类型,这里String.class表示返回结果是一个字符串。
@RestController
public class ClientController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/client")
public String client() {
//通过restTemplate请求rest服务端
String result = restTemplate.getForObject("http://localhost:8081/server", String.class);
return result;
}
getForEntity
- getForEntity和getForObject的用法是一样的,只是其返回结果是一个ResponseEntity,其中包含了更多的响应信息
ResponseEntity response = restTemplate.getForEntity("http://localhost:8081/server",String.class);
response.getHeaders(); //响应头
response.getStatusCode(); //响应码
response.getBody(); //响应体,即前面的result
postForObject
String response = restTemplate.postForObject("http://localhost:8081/server?param1={1}¶m2={2}", null, String.class, "hello", "world");
HttpEntity
//请求体
Map map = new HashMap();
map.put("param1", "hello");
map.put("param2", "world");
//请求头
MultiValueMap headers = new HttpHeaders();
headers.add("Accept", "text/xml");
//请求内容封装成httpEntity
HttpEntity httpEntity= new HttpEntity(map,headers);
restTemplate.postForObject("http://localhost:8081/server", httpEntity, String.class);
postForEntity
和getForEntity原理是一样的
配置超时
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = restTemplateBuilder
.setConnectTimeout(1000) //连接超时为1秒
.setReadTimeout(1000) //请求超时为1秒
.build();
return restTemplate;
}