使用Spring RestTemplate在每个请求中添加请求参数

4
我想使用RestTemplate在每个请求中添加常见的请求参数。例如,如果我的urlhttp://something.com/countries/US,那么我想添加常见的请求参数?id=12345。这个常见的请求参数需要被添加到所有请求中。我不想在每次调用时都添加它,而是想要一些通用的方法。 这篇文章有一个被标记为正确的答案,但我不确定如何在org.springframework.http.HttpRequest上添加请求参数。
有没有其他方法可以实现这个功能?
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;
    }
}

使用@ken-chan建议的拦截器代码添加请求参数。将创建一个新的Resttemaple实例,用于每个请求。

-1

您可以通过向RestTemplate添加拦截器来实现此操作


我知道那个。但我的问题是如何做到的。 - want2learn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接