Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate GET request remove empty query params

Tags:

java

spring

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

like image 293
sarvagya kumar Avatar asked Apr 18 '17 11:04

sarvagya kumar


1 Answers

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)
like image 69
StanislavL Avatar answered Nov 02 '22 20:11

StanislavL