getForObject 方法和 getForEntity 方法类似,getForObject 方法也有三个重载的方法,参数和 getForEntity 一样,因此这里我就不重复介绍参数了,这里主要说下 getForObject 和 getForEntity 的差异,这两个的差异主要体现在返回值的差异上, getForObject 的返回值就是服务提供者返回的数据,使用 getForObject 无法获取到响应头。
1、Get
1.1、无参
1.2、有参
第一种方式:
String url = "http://localhost:8080/rest/getUser?id={1}&name={2}&age={3}";ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class, 2, "lisi", 23);
第二种方式:
String url = "http://localhost:8080/rest/getUser?id={id}&name={name}&age={age}";Map<String, Object> map = new HashMap<>();map.put("id", 11);map.put("name", "kl");map.put("age", 123);ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class, map);
第三种方式
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);MultiValueMap<String, String> hashMap = new LinkedMultiValueMap<>();hashMap.add("start", Long.toString(start));hashMap.add("end", Long.toString(end));String uri = builder.queryParams(hashMap).build().encode().toString();ResponseEntity<String> forEntity = restTemplate.getForEntity(uri, String.class);
