我正在尝试使用
RestTemplate
将通用请求参数添加到每个请求。
例如,如果我的 url
是 http://something.com/countries/US
那么我想添加公共请求参数 ?id=12345
。所有请求都需要添加这个通用请求参数。我不想在每次通话中添加这个并想要一些通用的东西。
this 帖子的答案已标记为正确,但我不确定如何在
org.springframework.http.HttpRequest
上添加请求参数
还有其他方法可以实现这个目标吗?
要向
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);
使用 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;
}
}
您可以通过向剩余模板添加拦截器来实现此目的