'Spring RestTemplate GET request remove empty query params
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}¶m2={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¶m2= 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
Solution 1:[1]
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;
}
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rodrigo Dias |
| Solution 2 | lilalinux |
