七、通用请求方法:exchange
1,方法介绍
(1)exchange 的用法同前面介绍的 getForEntity、postForEntity 差不多,且返回的都是 ResponseEntity<T>:
- ResponseEntity<T> 是 Spring 对 HTTP 请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
- 其中响应消息体可以通过 ResponseEntity 对象的 getBody() 来获取。
(2)不同在于 exchange 方法提供统一的方法模板,可以通过指定不同的 HTTP 请求类型,实现 POST、PUT、DELETE、GET 四种请求。
2,Get 请求样例
(1)下面代码使用 Get 方式请求一个网络接口,并将响应体、响应头、响应码打印出来。其中响应体的类型设置为 String。
关于请求更详细的用法(包括参数传递、结果转成自定义对象),可以参考我之前写的文章:
@RestController
public class HelloController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/test")
public void test() {
String url = "http://jsonplaceholder.typicode.com/posts/5";
ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET,
null, String.class);
String body = responseEntity.getBody(); // 获取响应体
HttpStatus statusCode = responseEntity.getStatusCode(); // 获取响应码
int statusCodeValue = responseEntity.getStatusCodeValue(); // 获取响应码值
HttpHeaders headers = responseEntity.getHeaders(); // 获取响应头
System.out.println("body:" + body);
System.out.println("statusCode:" + statusCode);
System.out.println("statusCodeValue:" + statusCodeValue);
System.out.println("headers:" + headers);
return;
}
} 2)运行结果如下:

3,Post 请求样例
(1)下面代码使用 post 方式发送一个 JSON 格式的数据,并将响应体、响应头、响应码打印出来。其中响应体的类型设置为 String。
关于请求更详细的用法(包括 form 表单方式提交数据、将结果转成自定义对象),可以参考我之前写的文章:
@RestController
public class HelloController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/test")
public void test() {
// 请求地址
String url = "http://jsonplaceholder.typicode.com/posts";
// 请求头设置
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//提交参数设置
MultiValueMap map = new LinkedMultiValueMap<>();
map.add("userId", "222");
map.add("title", "abc");
map.add("body", "航歌");
// 组装请求体
HttpEntity> request =
new HttpEntity>(map, headers);
// 发送post请求,并输出结果
ResponseEntity responseEntity
= restTemplate.exchange(url, HttpMethod.POST, request, String.class);
String body = responseEntity.getBody(); // 获取响应体
HttpStatus statusCode = responseEntity.getStatusCode(); // 获取响应码
int statusCodeValue = responseEntity.getStatusCodeValue(); // 获取响应码值
HttpHeaders responseHeaders = responseEntity.getHeaders(); // 获取响应头
System.out.println("body:" + body);
System.out.println("statusCode:" + statusCode);
System.out.println("statusCodeValue:" + statusCodeValue);
System.out.println("headers:" + responseHeaders);
return;
}
} (2)运行结果如下:

原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2517.html