SpringBoot-29-RestTemplate的Get请求使用详解
RestTemplate的Htttp Get请求我们经常使用下面两个方法:
-
getForObject():返回Http协议的响应体
-
getForEntity():返回ResponseEntity,ResponseEntity对Http进行了封装,除了包含响应体以外,还包含Http状态码、contentType、Header等信息。
getForObject()方法的使用
以String方式进行请求
我们写一个接口代码如下,http://jsonplaceholder.typicode.com是一个免费的接口测试网站。
@RequestMapping("/test")
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("comments")
public String test(){
String forEntity = restTemplate.getForObject("http://jsonplaceholder.typicode.com/comments?author.name=typicode", String.class);
return forEntity;
}
}
测试http://localhost:8080/test/comments接口,结果为:
注:getForObject的第二个参数为返回结果类型。
以实体类型进行请求
还是上面的请求,但是我们新建一个实体类
@Data
public class TestEntity {
private int postId;
private int id;
private String name;
private String email;
private String body;
}
设计接口代码,因为返回对应是一个数组,所以我们的就收对象,要设置为TestEntity[]
@GetMapping("/comments/entity")
public TestEntity[] entity(){
TestEntity[] forEntity = restTemplate.getForObject("http://jsonplaceholder.typicode.com/comments?author.name=typicode", TestEntity[].class);
return forEntity;
}
使用占位符传递参数
- 使用占位符的形式传递参数
@GetMapping("/comments_2/{type}")
public TestEntity[] testentity_2(@PathVariable("type")String type){
TestEntity[] forEntity = restTemplate.getForObject("http://jsonplaceholder.typicode.com/comments?author.name={1}", TestEntity[].class,type);
return forEntity;
}
- 另一种形式传参
@GetMapping("/comments_1/{type}")
public TestEntity[] testentity_1(@PathVariable("type")String type){
TestEntity[] forEntity = restTemplate.getForObject("http://jsonplaceholder.typicode.com/comments?author.name={type}", TestEntity[].class,type);
return forEntity;
}
- 使用 map 装载参数
@GetMapping("/comments_map/{type}")
public TestEntity[] testentity_3(@PathVariable("type")String type){
Map<String,Object> map = new HashMap<>();
map.put("type",map);
TestEntity[] forEntity = restTemplate.getForObject("http://jsonplaceholder.typicode.com/comments?author.name={type}", TestEntity[].class,map);
return forEntity;
}
getForEntity()方法的使用
getForObject()所有的传参请求方式,getForEntity()都可以使用,使用方式也几乎一样。在返回结果上有区别,使用**ResponseEntity**来就收响应结果。
@GetMapping("/getForEntity/{type}")
public TestEntity[] getForEntity(@PathVariable("type")String type){
Map<String,Object> map = new HashMap<>();
map.put("type",map);
ResponseEntity<TestEntity[]> forEntity = restTemplate.getForEntity("http://jsonplaceholder.typicode.com/comments?author.name={type}", TestEntity[].class,map);
System.out.println("状态: " +forEntity.getStatusCode());
System.out.println("状态码: " +forEntity.getStatusCodeValue());
System.out.println("Headers: " +forEntity.getHeaders());
return forEntity.getBody();
}
测试返回结果会和上面的一样,但是在console会有输出
如果您觉得本文不错,欢迎关注,点赞,收藏支持,您的关注是我坚持的动力!
原创不易,转载请注明出处,感谢支持!如果本文对您有用,欢迎转发分享!