在RestTemplate中,对GET请求有以下两种方法
第一种是getForEntiy函数,返回的是ResponseEntity
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://service/user?name={1}", String.class, "username");
String body = responseEntity.getBody();
如果希望返回的body是个User对象,也可以这样实现:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://service/user?name={1}", User.class, "username");
User body = responseEntity.getBody();
getForEntiy函数共三种重载:
getForEntity(String url, Class responseType, Object... urlVariables), 就是上面的这种方式
getForEntity(String url, Class responseType, Map urlVariables)
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<>();
params.put("name", "username");
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://service/user?name={name}", String.class, params);
注意map的key要和参数中占位符相同
- getForEntity(URI uri, Class responseType)
RestTemplate restTemplate = new RestTemplate();
UriComponents uriConponents = UriComponentsBuilder.fromUriString("http://service/user?name={name}").build().expand("username").encode();
URI uri = uriConponents.toUri();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
第二种是getForObject函数, 可以看作是对getForEntity进一步封装
RestTemplate restTemplate = new RestTemplate();
//注意参数中是uri不是url
String body = restTemplate.getForObject(uri, String.class);
返回User对象:
RestTemplate restTemplate = new RestTemplate();
User body = restTemplate.getForObject(uri, User.class);
该方法也是三种重载参照getForEntity
此外,RestTemplate的POST方法也分为postForEntity和postForObject,各有三种重载,使用方法和GET方法基本一一对应