使用 Spring RestTemplate 调用 rest 服务时自定义请求头(custom HTTP headers)

本文介绍了如何在Spring3.0及3.1中通过HttpEntity和ClientHttpRequestInterceptor接口自定义HTTP头部信息,实现发送带有特定接受类型的应用/pdf请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 Spring 3.0 中可以通过 HttpEntity 对象自定义请求头信息,如:
private static final String APPLICATION_PDF = "application/pdf";
 
RestTemplate restTemplate = new RestTemplate();
 
@Test
public void acceptHeaderUsingHttpEntity() throws Exception {
  HttpHeaders headers = new HttpHeaders();
  headers.setAccept(singletonList(MediaType.valueOf(APPLICATION_PDF)));
 
  ResponseEntity<byte[]> response = restTemplate.exchange("http://example.com/file/123",
      GET,
      new HttpEntity<byte[]>(headers),
      byte[].class);
 
  String responseText = PdfTextExtractor.getTextFromPage(new PdfReader(response.getBody()), 1);
  assertEquals("Some text in PDF file", responseText);
}
在 Spring 3.1 中有了一个更强大的替代接口 ClientHttpRequestInterceptor,这个接口只有一个方法: intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution),下面是一个例子:
private static final String APPLICATION_PDF = "application/pdf";
 
RestTemplate restTemplate = new RestTemplate();
 
@Test
public void acceptHeaderUsingHttpRequestInterceptors() throws Exception {
  ClientHttpRequestInterceptor acceptHeaderPdf = new AcceptHeaderHttpRequestInterceptor(
      APPLICATION_PDF);
 
  restTemplate.setInterceptors(singletonList(acceptHeaderPdf));
 
  byte[] response = restTemplate.getForObject("http://example.com/file/123", byte[].class);
 
  String responseText = PdfTextExtractor.getTextFromPage(new PdfReader(response), 1);
  assertEquals("Some text in PDF file", responseText);
}
 
class AcceptHeaderHttpRequestInterceptor implements ClientHttpRequestInterceptor {
  private final String headerValue;
 
  public AcceptHeaderHttpRequestInterceptor(String headerValue) {
    this.headerValue = headerValue;
  }
 
  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body,
      ClientHttpRequestExecution execution) throws IOException {
 
    HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
    requestWrapper.getHeaders().setAccept(singletonList(MediaType.valueOf(headerValue)));
 
    return execution.execute(requestWrapper, body);
  }
}


原文:http://svenfila.wordpress.com/2012/01/05/resttemplate-with-custom-http-headers/

### 如何在 Spring MVC 中使用 RestTemplate 进行 HTTP 请求操作 `RestTemplate` 是 Spring 提供的一个同步客户端,用于执行 HTTP 请求。它可以轻松地发送 GET、POST、PUT 和 DELETE 等类型的请求,并处理响应数据。 以下是关于 `RestTemplate` 的基本使用方法以及一个完整的示例: #### 导入依赖 为了在项目中使用 `RestTemplate`,需要确保项目的构建文件(如 Maven 或 Gradle)已包含必要的 Spring Web 依赖项[^2]。 对于 Maven 用户: ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.10</version> </dependency> ``` 对于 Gradle 用户: ```gradle implementation 'org.springframework:spring-web:5.3.10' ``` --- #### 创建并配置 RestTemplate 实例 可以通过直接实例化 `RestTemplate` 来创建对象,或者将其声明为 Spring Bean 并注入到其他组件中。 ```java import org.springframework.web.client.RestTemplate; public class RestClient { private final RestTemplate restTemplate = new RestTemplate(); public String fetchUserDetails(String userId) { String url = "https://api.example.com/users/{userId}"; return restTemplate.getForObject(url, String.class, userId); } } ``` 在此代码片段中,`getForObject()` 方法被用来发起一个带有路径参数的 GET 请求[^2]。 --- #### 处理复杂场景下的请求 当涉及到更复杂的 HTTP 请求,可以利用以下功能来增强灵活性: ##### 发送 POST 请求 如果需要向服务器提交 JSON 数据,则可以使用 `postForEntity()` 方法。 ```java import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class PostRequestExample { private static final RestTemplate restTemplate = new RestTemplate(); public ResponseEntity<String> createUser(User user) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<User> request = new HttpEntity<>(user, headers); String url = "https://api.example.com/users"; return restTemplate.postForEntity(url, request, String.class); } // 假设 User 类已经定义好 public static class User { private String name; private int age; // Getters and Setters omitted for brevity } } ``` 此代码展示了如何通过设置自定义头信息和传递实体体内容完成 POST 请求的操作[^2]。 --- #### 配置超和其他高级选项 默认情况下,`RestTemplate` 不会自动应用连接或读取超间。这可能会影响应用程序性能,尤其是在网络状况不佳的情况下。因此建议显式指定这些属性。 ```java import java.time.Duration; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; public class CustomizedRestTemplateConfig { public RestTemplate createCustomizedRestTemplate() { CloseableHttpClient httpClient = HttpClients.custom() .setConnectionTimeToLive(Duration.ofSeconds(30)) .build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); factory.setConnectTimeout(5000); // 设置连接超间为 5 秒钟 factory.setReadTimeout(10000); // 设置读取超间为 10 秒钟 return new RestTemplate(factory); } } ``` 以上实现方式基于 Apache HttpClient 构建了一个具有特定行为特性的 `RestTemplate` 实例[^2]。 --- #### 测试 REST API 调用逻辑 借助于之前提到过的 **Spring MVC Test Framework**[^1],可以在单元测试阶段验证控制器的行为是否符合预期,而无需实际部署整个应用环境。 假设我们有一个简单的 Controller 接口如下所示: ```java @RestController @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public String getUserById(@PathVariable String id) { return "User with ID: " + id; } } ``` 那么对应的 MockMvc 单元测试可能是这样的形式: ```java @WebMvcTest(UserController.class) class UserControllerTests { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; // 如果存在服务层的话也需要模拟出来 @Test void testGetUserById() throws Exception { this.mockMvc.perform(get("/users/1")) .andExpect(status().isOk()) .andExpect(content().string("User with ID: 1")); } } ``` 这里运用到了 Spring Boot Testing 功能的一部分[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值