restTemplate get请求添加请求头
时间: 2024-03-01 20:45:47 浏览: 79
Spring学习笔记之RestTemplate使用小结
使用RestTemplate的exchange方法来发送带有请求头的GET请求。具体步骤如下:
1. 创建HttpHeaders对象,并设置请求头信息。
```java
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer token");
```
2. 创建HttpEntity对象,并将HttpHeaders对象设置到其中。
```java
HttpEntity<String> entity = new HttpEntity<>(headers);
```
3. 调用RestTemplate的exchange方法发送GET请求,并将HttpEntity对象作为参数传入。
```java
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
```
完整代码示例:
```java
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api";
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer token");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
String responseBody = response.getBody();
```
阅读全文