如何正确使用RestTemplate【六】

203

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

复习一下下

上篇文章,我们学习了HEAD请求的相关方法的使用方法,以及具体参数的不同,当然还有一些代码示例、使用场景等等,你是否还有些印象呢?

RestTemplate今日知识

今天我们来学习POST请求的使用方法,来共同学习一下吧。

请求方法参数分析

POST请求

共有参数介绍:

url:访问链接Url,不过多解释。

request:用于传输要新增的资源对象,比如一个用户User对象。

responseType:返回响应的参数类型,比如,返回的参数是个List,那么这个参数就应该传List.class。

uriVariables:url关联的一些参数

postForLocation

1.public URI postForLocation(String url, Object request, Object... uriVariables)

此方法需要传输url、请求对象、参数值三个参数,直接上代码示例:

User user = new User(1, 'username', 22);
URI uri = restTemplate.postForLocation(url, user, "first param","two param");

2.public URI postForLocation(String url, Object request, Map<String, ?> uriVariables)

此方法需要传输url、请求对象、Map参数值三个参数,直接上代码示例:

Map<String,String> map = new HashMap<>;
map.put("Frist","first param");
map.put("Two","two param");
User user = new User(1, 'username', 22);
URI uri = restTemplate.postForLocation(url, user, map);

3.public URI postForLocation(URI url, Object request)

此方法需要传输url和请求对象即可。

postForObject

1.public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)

此方法需要传输url、请求对象、返回参数类型class、参数值四个参数,直接上代码示例:

User user = new User(1, 'username', 22);
List list = restTemplate.postForObject(url, user, List.class, "first param","two param");

2.public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)

此方法需要传输url、请求对象、返回参数类型class、参数值四个参数,直接上代码示例:

Map<String,String> map = new HashMap<>;
map.put("Frist","first param");
map.put("Two","two param");
User user = new User(1, 'username', 22);
List list = restTemplate.postForObject(url, user, List.class, map);

3.public <T> T postForObject(URI url, Object request, Class<T> responseType)

此方法需要传输url、请求对象、返回参数类型class、参数值三个参数

getForEntity

getForEntiy,除了返回的参数的不同之外,没有什么的区别,不做过多的解释,给个代码示例自己学习吧。

1.public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)

此方法需要传输url、请求对象、返回参数类型class、参数值四个参数,直接上代码示例:

User user = new User(1, 'username', 22);
ResponseEntity<List> entity = restTemplate.postForEntity(url, user, List.class,"first param","two param");
System.out.println(entity.getBody());

2.public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)

Map<String,String> map = new HashMap<>;
map.put("Frist","first param");
map.put("Two","two param");
User user = new User(1, 'username', 22);
ResponseEntity<List> entity = restTemplate.postForEntity(url, user, List.class, map);
System.out.println(entity.getBody());

3.public <T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType)

这个就不用说了吧,哈哈哈哈。

使用场景

POST请求的使用场景太多了,在这就不赘述了。

小结

今天我们又学习了POST请求相关方法的使用方式,你是否有所收获呢?