四、POST 请求1:postForObject() 方法的使用
1,方法介绍
postForObject() 用于发送一个 HTTP POST 请求。它和 postForEntity() 用法几乎相同。区别在于 postForObject() 返回值返回的是响应体,省略了很多 response 的信息。
2,发送一个 JSON 格式数据
(1)下面代码使用 post 方式发送一个 Bean 对象,并将结果打印出来(以字符串的形式)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
(2)上面发送的 Bean 对象实际上会转成如下格式的 JSON 数据提交:
3,使用 Form 表单的形式提交数据
(1)下面样例使用 POST 方式发送 multipart/form-data 格式的数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
(2)上面代码最终会通过如下这种 form 表单方式提交数据:
4,将结果转成自定义对象
上面样例我们都是将响应结果以 String 形式接收,其实 RestTemplate 还可以自动将响应结果转成自定的对象或则数组。
5,设置 url 参数
(1)如果 url 地址上面需要传递一些参数,可以使用占位符的方式:
1 2 | |
五、POST 请求2:postForEntity()方法的使用
1,方法介绍
postForEntity() 用于发送一个 HTTP POST 请求。它和上面的 postForObject() 用法几乎相同。区别在于 getForEntity() 返回的是 ResponseEntity<T>:
- ResponseEntity<T> 是 Spring 对 HTTP 请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
- 其中响应消息体可以通过 ResponseEntity 对象的 getBody() 来获取。
2,发送一个 JSON 格式数据
(1)下面代码使用 post 方式发送一个 Bean 对象,并将响应体、响应头、响应码打印出来。其中响应体的类型设置为 String。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
(2)上面发送的 Bean 对象实际上会转成如下格式的 JSON 数据提交:
3,使用 Form 表单的形式提交数据
(1)下面样例使用 POST 方式发送 multipart/form-data 格式的数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
(2)上面代码最终会通过如下这种 form 表单方式提交数据:
4,将结果转成自定义对象
上面样例我们都是将响应结果以 String 形式接收,其实 RestTemplate 还可以自动将响应结果转成自定的对象或则数组。
5,设置 url 参数
(1)如果 url 地址上面需要传递一些参数,可以使用占位符的方式:
1 2 | |
六、POST 请求3:postForLocation() 方法的使用
1,方法介绍
(1)postForLocation() 也是通过 Post 方式提交新资源,postForLocation() 方法的参数和前面两种(postForObject、postForEntity)的参数基本一致。
(2)区别在于 postForLocation() 方法的返回值为 Uri,这个只需要服务提供者返回一个 Uri 即可,该 Uri 表示新资源的位置。
2,使用样例
(1)比如通常登录或者注册都是 post 请求,而这些操作完成之后大部分都是跳转到别的页面去了。这种场景下,就可以使用 postForLocation 了,提交数据,并获取返回的 URI。
(2)下面是一个简单的样例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
参考文章:www.hangge.com