javaspringrestspring-bootresttemplate

Add Query Parameter to Every REST Request using Spring RestTemplate


Is there a way to add a query parameter to every HTTP request performed by RestTemplate in Spring?

The Atlassian API uses the query parameter os_authType to dictate the authentication method so I'd like to append ?os_authtype=basic to every request without specifying it all over my code.

Code

@Service
public class MyService {

    private RestTemplate restTemplate;

    @Autowired
    public MyService(RestTemplateBuilder restTemplateBuilder, 
            @Value("${api.username}") final String username, @Value("${api.password}") final String password, @Value("${api.url}") final String url ) {
        restTemplate = restTemplateBuilder
                .basicAuthorization(username, password)
                .rootUri(url)
                .build();    
    }

    public ResponseEntity<String> getApplicationData() {            
        ResponseEntity<String> response
          = restTemplate.getForEntity("/demo?os_authType=basic", String.class);

        return response;    
    }
}

Solution

  • You can write custom RequestInterceptor that implements ClientHttpRequestInterceptor

    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpRequest;
    import org.springframework.http.client.ClientHttpRequestExecution;
    import org.springframework.http.client.ClientHttpRequestInterceptor;
    import org.springframework.http.client.ClientHttpResponse;
    
    public class AtlassianAuthInterceptor implements ClientHttpRequestInterceptor {
    
        @Override
        public ClientHttpResponse intercept(
                HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                throws IOException {
    
            // logic to check if request has query parameter else add it
            return execution.execute(request, body);
        }
    }
    

    Now we need to configure our RestTemplate to use it

    import java.util.Collections;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.client.ClientHttpRequestInterceptor;
    import org.springframework.web.client.RestTemplate;
    
    
    @Configuration
    public class MyAppConfig {
    
        @Bean
        public RestTemplate restTemplate() {
            RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
            restTemplate.setInterceptors(Collections.singletonList(new AtlassianAuthInterceptor()));
            return restTemplate;
        }
    }