Java 中使用 RestTemplate 传递 HTTP Header 有多种方式,以下是常用的几种方法:

1. 使用 HttpHeaders 和 HttpEntity(推荐)

java

复制

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    
    public void sendRequestWithHeaders() {
        RestTemplate restTemplate = new RestTemplate();
        
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer your_token_here");
        headers.set("Content-Type", "application/json");
        headers.set("X-Custom-Header", "custom_value");
        
        // 如果有多个相同名称的header,使用add
        headers.add("X-Request-ID", "uuid-123");
        
        // 创建请求实体(body可以是null对于GET请求)
        HttpEntity<String> entity = new HttpEntity<>(headers);
        
        // 发送GET请求
        ResponseEntity<String> response = restTemplate.exchange(
            "https://api.example.com/data",
            HttpMethod.GET,
            entity,
            String.class
        );
        
        String result = response.getBody();
    }
}

2. POST 请求带 Header 和 Body

java

复制

public void postWithHeaders() {
    RestTemplate restTemplate = new RestTemplate();
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setBearerAuth("your_jwt_token"); // 设置Bearer Token
    
    // 请求体
    String jsonBody = "{\"name\":\"test\",\"value\":123}";
    
    // 组合header和body
    HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
    
    ResponseEntity<String> response = restTemplate.postForEntity(
        "https://api.example.com/create",
        entity,
        String.class
    );
}

3. 使用 ClientHttpRequestInterceptor(全局配置)

如果需要为所有请求添加相同的 Header(如统一的认证信息):

java

复制

import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.support.HttpRequestWrapper;

public class RestTemplateConfig {
    
    public RestTemplate createRestTemplateWithInterceptor() {
        RestTemplate restTemplate = new RestTemplate();
        
        // 添加拦截器
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().set("Authorization", "Bearer " + getToken());
            request.getHeaders().set("X-API-Key", "your_api_key");
            return execution.execute(request, body);
        });
        
        return restTemplate;
    }
    
    private String getToken() {
        // 获取token的逻辑
        return "dynamic_token";
    }
}

4. 使用 RequestCallback(更底层控制)

java

复制

public void requestWithCallback() {
    RestTemplate restTemplate = new RestTemplate();
    
    RequestCallback requestCallback = request -> {
        request.getHeaders().set("Authorization", "Bearer token123");
        // 可以在这里写入body
    };
    
    ResponseExtractor<String> responseExtractor = 
        response -> new String(response.getBody().readAllBytes());
    
    String result = restTemplate.execute(
        "https://api.example.com/data",
        HttpMethod.GET,
        requestCallback,
        responseExtractor
    );
}

5. 使用 UriComponentsBuilder + Header

java

复制

public void getWithParamsAndHeaders() {
    RestTemplate restTemplate = new RestTemplate();
    
    // 构建URL
    String url = UriComponentsBuilder
        .fromHttpUrl("https://api.example.com/search")
        .queryParam("page", 1)
        .queryParam("size", 10)
        .toUriString();
    
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/json");
    
    HttpEntity<Void> entity = new HttpEntity<>(headers);
    
    ResponseEntity<String> response = restTemplate.exchange(
        url,
        HttpMethod.GET,
        entity,
        String.class
    );
}

常用 Header 设置方法

表格

复制

方法 说明
headers.set(key, value) 设置单个header(覆盖已有)
headers.add(key, value) 添加header(支持多值)
headers.setContentType(MediaType) 设置Content-Type
headers.setBearerAuth(token) 设置Bearer认证
headers.setBasicAuth(username, password) 设置Basic认证
headers.setAll(Map) 批量设置

注意事项

  1. Spring Boot 3.x / Spring 6+RestTemplate 已被标记为弃用,建议迁移到 WebClient(响应式)或 RestClient(Spring 6.1+)

  2. 线程安全RestTemplate 是线程安全的,建议配置为单例

  3. 编码问题:中文内容建议设置 MediaType.APPLICATION_JSON_UTF8

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐