wan*_*arn 3 resttemplate spring-boot
我正在尝试使用RestTemplate. 例如,如果我url是http://something.com/countries/US那么我想添加 common request param ?id=12345。需要在所有请求上添加此通用请求参数。我不想在每次通话时都添加这个,想要一些共同点。
这篇文章的答案被标记为正确,但我不确定如何添加请求参数org.springframework.http.HttpRequest
我可以通过任何其他方式实现这一目标吗?
Ken*_*han 10
要将请求参数添加到 中HttpRequest,您可以先使用在现有的基础上UriComponentsBuilder构建一个新URI的URI但添加您要添加的查询参数。
然后用于HttpRequestWrapper包装现有请求,但仅URI使用更新的URI.
代码明智它看起来像:
public class AddQueryParamterInterceptor 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);
}
}
Run Code Online (Sandbox Code Playgroud)
并将此拦截器设置为RestTemplate:
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new AddQueryParamterInterceptor());
restTemplate.setInterceptors(interceptors);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1724 次 |
| 最近记录: |