使用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
相关产品推荐
相关产品推荐

