spring-bootresttemplate

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 ?


Solution

  • 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);