Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding request param to every request using spring resttemplate

I am trying to add common request parameters to every request using RestTemplate. For example if my url is http://something.com/countries/US then I want to add common request param ?id=12345. This common request parameter needs to be added on all request. I don't want to add this on each call and want something common.

this post has answer that was marked correct, but I am not sure how you can add request parameters on org.springframework.http.HttpRequest

Any other way I can achieve this ?

like image 536
want2learn Avatar asked Jul 15 '26 02:07

want2learn


2 Answers

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);
like image 95
Ken Chan Avatar answered Jul 17 '26 16:07

Ken Chan


for Spring 6.1 / Spring Boot 3.2.x

    // inject apikey in URI query parameter
    ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {

        HttpRequest modifiedRequest = new HttpRequestWrapper(request) {

            @Override
            public URI getURI() {
                return ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders())
                        .queryParam("apikey", omdbApikey)
                        .build(true)
                        .toUri();
            }
        };

        return execution.execute(modifiedRequest, body);
    };

The interceptor can be used in a RestTemplate/WebClient/RestClient

example:

        RestClient restClient = RestClient.Builder
                .requestInterceptor(interceptor)
                .build();
like image 42
d2k2 Avatar answered Jul 17 '26 15:07

d2k2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!