6
votes

I want to make REST call using spring RestTemplate, the URL contains some optional query params. The URL looks something like

url = example.com/param1={param1}&param2={param2}

I pass params as map to restTemplate using exchange method

restTemplate.exchange(url, method, payLoad, String.class, params)

The final URL is example.com/param1=somevalue&param2= since param2 was not present in params map.

I want to remove param2 from the request, that is, the final URL should contain only param1 and URL should look like example.com/param1=somevalue

3

3 Answers

4
votes

You can use UriComponentsBuilder and provide desired params (not nulls).

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("example.com");
builder.replaceQueryParam("param1", param1value);
...
restTemplate.exchange(builder.build().encode().toUri(),
                    httpMethod,
                    requestEntity,
                    String.class)
0
votes

You can use the method UriComponentsBuilder.replaceQueryParam()

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("example.com")
              .replaceQueryParam("param1", null);
              .replaceQueryParam("param2", "Hello");

This will output example.com?param2=Hello and ignore the param1's value

0
votes

You can make a class that delegates calls to UriComponentsBuilder. With a method like:

public UriBuilder queryParam(String name, String value) {

    if (!StringUtils.isEmpty(value)){
        internalBuilder.queryParam(name, value);
    }else {
        //or dont do anything
        internalBuilder.replaceQueryParam(name);
    }

    return this;
}