To add request parameters to the HttpRequest
, you can first use UriComponentsBuilder
to build an new URI
based on the existing URI
but adding the query parameters that you want to add.
Then use HttpRequestWrapper
to wrap the existing request but only override its URI
with the updated URI
.
Code wise it looks like:
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);
}
}
And add the interceptor to the RestTemplate
:
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new AddQueryParamterInterceptor());
restTemplate.setInterceptors(interceptors);