Search code examples
javaresttemplateurl-parametersquery-stringpath-parameter

RestTemplate: How to send URL and query parameters together


I am trying to pass path param and query params in a URL but I am getting a weird error. Below is the code.

    String url = "http://test.com/Services/rest/{id}/Identifier"
    Map<String, String> params = new HashMap<String, String>();
    params.put("id", "1234");
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                                        .queryParam("name", "myName");
    String uriBuilder = builder.build().encode().toUriString();
    restTemplate.exchange(uriBuilder , HttpMethod.PUT, requestEntity,
                    class_p, params);

and my url is becoming http://test.com/Services/rest/%7Bid%7D/Identifier?name=myName

What should I do to make it work? I am expecting http://test.com/Services/rest/{id}/Identifier?name=myName so that params will add id to the url.


Solution

  • I would use buildAndExpand from UriComponentsBuilder to pass all types of URI parameters.

    For example:

    String url = "http://test.com/solarSystem/planets/{planet}/moons/{moon}";
    
    // URI (URL) parameters
    Map<String, String> urlParams = new HashMap<>();
    urlParams.put("planet", "Mars");
    urlParams.put("moon", "Phobos");
    
    // Query parameters
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
            // Add query parameter
            .queryParam("firstName", "Mark")
            .queryParam("lastName", "Watney");
    
    System.out.println(builder.buildAndExpand(urlParams).toUri());
    /**
     * Console output:
     * http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney
     */
    
    restTemplate.exchange(builder.buildAndExpand(urlParams).toUri() , HttpMethod.PUT,
            requestEntity, class_p);
    
    /**
     * Log entry:
     * org.springframework.web.client.RestTemplate Created PUT request for "http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney"
     */