You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spring RestTemplate.exchange时如何设置HTTP/1.1协议版本?

解决方案:为RestTemplate配置HTTP/1.1协议版本

在Apache HttpClient 4.3及以上版本中,getParams()方法确实已被废弃,不过我们可以通过**RequestConfig和HttpClientBuilder**这两个新API来配置HTTP协议版本,完美替代旧的参数设置方式。下面是针对你的代码的完整修改方案:

修改后的代码示例

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Autowired;

public class FooService {

    @Autowired
    private RestTemplate restTemplate;

    // 配置全局使用HTTP/1.1的CloseableHttpClient
    @Bean
    public CloseableHttpClient httpClient() {
        // 构建请求配置,强制指定HTTP协议版本为1.1
        RequestConfig requestConfig = RequestConfig.custom()
                .setProtocolVersion(org.apache.http.HttpVersion.HTTP_1_1)
                .build();

        // 通过HttpClientBuilder绑定默认配置,生成客户端实例
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient());
        return new RestTemplate(requestFactory);
    }

    public ResponseEntity<Foo> getResponse(String fooResourceUrl) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(headers);

        return restTemplate.exchange(
                fooResourceUrl,
                HttpMethod.GET,
                entity,
                Foo.class
        );
    }
}

核心要点说明

  • RequestConfig替代废弃的getParams():用RequestConfig.custom().setProtocolVersion(HTTP_1_1)来指定协议版本,这是HttpClient 4.3+推荐的配置方式。
  • 全局生效的配置:通过HttpClientBuilder.setDefaultRequestConfig()把HTTP/1.1设置为所有请求的默认协议,这样所有通过该RestTemplate发送的请求都会自动使用HTTP/1.1,无需单独配置每个请求。
  • 我调整了getResponse方法,把fooResourceUrl作为参数传入,让代码更灵活(你可以根据自己的业务场景调整回原来的写法)。

如果后续需要针对单个请求单独修改协议版本,也可以通过自定义HttpRequestInterceptor或者手动修改请求对象实现,但全局配置已经能解决你当前的问题。

内容的提问来源于stack exchange,提问作者dhinu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:27:38