2. 概述

本文将介绍如何在Apache HttpClient中设置自定义HTTP头。如果你想深入探索HttpClient的更多高级用法,可以参考HttpClient完整教程

3. 在单个请求中设置Header

通过简单的setHeader方法即可为请求添加自定义头:

@Test
void whenRequestHasCustomContentType_thenCorrect() throws IOException {
    final HttpGet request = new HttpGet(SAMPLE_URL);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        String response = client.execute(request, new BasicHttpClientResponseHandler());
        //处理响应数据
    }
}

如代码所示,我们直接在请求对象上设置了Content-Type为JSON格式。✅ 这种方式简单直接,适合单次请求的场景。

4. 使用HttpClient 4.5的RequestBuilder设置Header

在HttpClient 4.5版本中,推荐使用RequestBuilder来构建请求并设置Header:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
    .setUri(SAMPLE_URL)
    .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
    .build();
client.execute(request);

通过链式调用setHeader方法,代码更简洁易读。⚠️ 注意:这种方式需要HttpClient 4.5+版本支持。

5. 在客户端设置默认Header

与其为每个请求单独设置Header,不如直接在客户端配置默认Header:

@Test
void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws IOException {
    final HttpGet request = new HttpGet(SAMPLE_URL);
    final Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    final List<Header> headers = Lists.newArrayList(header);
    
    try (CloseableHttpClient client = HttpClients.custom()
        .setDefaultHeaders(headers)
        .build()) {
        
        String response = client.execute(request, new BasicHttpClientResponseHandler());
       //处理响应数据
    }
}

这种配置方式特别适合需要全局统一Header的场景,比如:

  • ✅ 自定义应用标识头
  • ✅ 统一的认证信息
  • ✅ 跨服务调用的追踪ID

6. 总结

本文展示了三种为Apache HttpClient添加HTTP头的方式:

  1. 单次请求设置(灵活但重复)
  2. RequestBuilder链式调用(代码简洁)
  3. 客户端默认配置(全局统一)

所有示例代码可在GitHub项目中找到,HttpClient 4相关示例请查看Apache HttpClient 4模块。实际开发中根据需求选择合适方案,避免踩坑!


原始标题:Custom HTTP Header with the Apache HttpClient

« 上一篇: Baeldung Weekly3
» 下一篇: Baeldung 周报4