java RestTemplate设置请求头headers
时间: 2023-11-02 20:59:05 浏览: 70
要在Java中使用RestTemplate设置请求头headers,你可以使用`HttpHeaders`类来创建和设置请求头。下面是一个示例代码:
```java
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class Main {
public static void main(String[] args) {
String url = "http://example.com/api";
// 创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
// 创建HttpHeaders对象,并设置Content-Type为application/json
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 创建HttpEntity对象,并设置请求头
HttpEntity<String> entity = new HttpEntity<>(headers);
// 发送GET请求,获取ResponseEntity对象
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
// 获取响应数据
String responseBody = response.getBody();
System.out.println(responseBody);
}
}
```
在上述示例中,我们通过创建一个`HttpHeaders`对象并设置`Content-Type`为`application/json`来设置请求头。然后,我们创建一个`HttpEntity`对象,并将之前创建的`HttpHeaders`对象作为参数传递给它。接下来,我们使用`RestTemplate`的`exchange`方法发送带有自定义请求头的GET请求,并获取到响应数据。
你可以根据自己的需求修改请求方法、请求体等。希望对你有帮助!
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)