Spring RestTemplate 发起 HTTP 请求:GET、POST、自定义 Header 与超时配置

配置 Bean

@Configuration
public class RestConfig {

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(10000);
        return new RestTemplate(factory);
    }
}

然后在 Service/Controller 中注入:

@Autowired
private RestTemplate restTemplate;

GET 请求

简单 GET:

String result = restTemplate.getForObject(
    "https://api.example.com/users/1",
    String.class
);

带路径参数:

String result = restTemplate.getForObject(
    "https://api.example.com/users/{id}",
    String.class,
    1
);

返回实体类(需要 Jackson):

@Data
public class User {
    private Integer id;
    private String name;
}

User user = restTemplate.getForObject(
    "https://api.example.com/users/1",
    User.class
);

POST 请求

发送 JSON:

Map<String, Object> body = new HashMap<>();
body.put("username", "admin");
body.put("password", "secret");

String result = restTemplate.postForObject(
    "https://api.example.com/login",
    body,
    String.class
);

自定义 Header(带 Token)

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer your-token");

Map<String, Object> body = new HashMap<>();
body.put("name", "test");

HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

ResponseEntity<String> response = restTemplate.exchange(
    "https://api.example.com/data",
    HttpMethod.POST,
    entity,
    String.class
);

String responseBody = response.getBody();
int statusCode = response.getStatusCode().value();

GET 请求带 Header

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer your-token");

HttpEntity<Void> entity = new HttpEntity<>(headers);

ResponseEntity<String> response = restTemplate.exchange(
    "https://api.example.com/profile",
    HttpMethod.GET,
    entity,
    String.class
);

处理异常

try {
    String result = restTemplate.getForObject(url, String.class);
} catch (HttpClientErrorException e) {
    // 4xx 错误
    System.out.println("HTTP " + e.getStatusCode() + ": " + e.getResponseBodyAsString());
} catch (HttpServerErrorException e) {
    // 5xx 错误
    System.out.println("Server error: " + e.getMessage());
} catch (ResourceAccessException e) {
    // 连接超时、网络错误
    System.out.println("Connection error: " + e.getMessage());
}

Spring Boot 3 注意

RestTemplate 已进入维护模式,Spring Boot 3 推荐使用 WebClient(响应式)或 Spring 6.1 引入的 RestClient(同步):

// RestClient(Spring 6.1+)
RestClient client = RestClient.create();
String result = client.get()
    .uri("https://api.example.com/users/1")
    .retrieve()
    .body(String.class);

老项目继续使用 RestTemplate 完全没问题,新项目可以考虑迁移到 RestClient