使用 Spring RestTemplate 将请求参数添加到每个请求

问题描述 投票:0回答:3

我正在尝试使用

RestTemplate
将通用请求参数添加到每个请求。 例如,如果我的
url
http://something.com/countries/US
那么我想添加公共请求参数
?id=12345
。所有请求都需要添加这个通用请求参数。我不想在每次通话中添加这个并想要一些通用的东西。

this 帖子的答案已标记为正确,但我不确定如何在

org.springframework.http.HttpRequest

上添加请求参数

还有其他方法可以实现这个目标吗?

spring-boot resttemplate
3个回答
14
投票

要向

HttpRequest
添加请求参数,您可以先使用
UriComponentsBuilder
在现有
URI
的基础上构建新的
URI
,但添加您要添加的查询参数。

然后使用

HttpRequestWrapper
包装现有请求,但仅使用更新的
URI
覆盖其
URI

从代码角度看,它看起来像:


public class AddQueryParameterInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {

        URI uri = UriComponentsBuilder.fromHttpRequest(request)
                .queryParam("id", 12345)
                .build().toUri();
        
        HttpRequest modifiedRequest = new HttpRequestWrapper(request) {
        
            @Override
            public URI getURI() {
                return uri;
            }
        };
        return execution.execute(modifiedRequest, body);
    }

}

并将拦截器添加到

RestTemplate

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new AddQueryParamterInterceptor());

restTemplate.setInterceptors(interceptors);

0
投票

使用 RestTemplate 向每个请求添加通用请求参数需要做两件事。

  1. 创建原型 bean RestTemplate
@Configuration
public class RestTemplateConfig {
    @Bean
    @Scope(
            value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
            proxyMode = ScopedProxyMode.TARGET_CLASS)
    public RestTemplate restTemplate() {
        RestTemplate localRestTemplate = new RestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = localRestTemplate.getInterceptors();
        if (CollectionUtils.isEmpty(interceptors)) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new AddQueryParamterInterceptor());
        localRestTemplate.setInterceptors(interceptors);
        return localRestTemplate;
    }
}
  1. 使用@ken-chan建议的拦截器代码添加请求参数。将为每个请求创建一个新的 Resttemaple 实例。

-1
投票

您可以通过向剩余模板添加拦截器来实现此目的

© www.soinside.com 2019 - 2024. All rights reserved.