Get请求
getForEntity
类方法返回的数据类型为 ResponseEntity<T>
, 然后重载方法, 以不同的方式传递参数
getForEntity(String url, Class<T> responseType, Object... uriVariables)
getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)
getForEntity(URI url, Class<T> responseType)
示例:
1 | // 1 |
如果希望接口直接返回需要的数据类型, 则可以使用下面这组方法, 返回的数据类型就是传入的T
getForObject(String url, Class<T> responseType, Object... uriVariables)
getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)
getForObject(URI url, Class<T> responseType)
示例:
1 | // 1 |
Post
Post和Get方法一样, 有postForObject
和postForEntity
方法
postForObject(URI url, @Nullable Object request, Class<T> responseType)
postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
postForEntity
类方法
postForEntity(URI url, @Nullable Object request, Class<T> responseType)
postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
除此之外, 还有postForLocation
, 但是这类方法的返回值为URI
, 没法接收响应体
exchange
这组方法偏底层, 比如需要设置请求头时使用
exchange(RequestEntity<?> requestEntity, Class<T> responseType)
exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType)
exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables)
参数示例:
1 | // URI构造方式 |
请求示例:
1 | // 1 |
下面这类方法是为了支持泛型, 比如, 返回数据类型是List, 但用上面方法无法进一步设置List内元素类型
exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables)
exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables)