Abhinav Manthri
Abhinav Manthri

Reputation: 348

How to call GET api with query params having special chars{&,(,),'} using spring rest template

Below was the code used to encode uri having query params using UriComponentsBuilder

String uri = "http://hostname/api/items"
// api expected with params --> http://hostname/api/items?filter=IN('123') and id eq '123_&123'
restTemplate.exchange(UriComponentsBuilder.fromUriString(uri).queryParam("filter","IN('123') and id eq '123_&123'").encode().toUriString(), HttpMethod.GET, request, Response_Entity.class)

When above code is called, somehow at api side, i was getting 2 query params with keys -->filter & 123

How to handle it correctly using ?

Upvotes: 0

Views: 1858

Answers (2)

Abhinav Manthri
Abhinav Manthri

Reputation: 348

Somehow query params are encoded and at api side, by default these are retrieved correctly after decoding, if i use toURI() of UriComponentsBuilder

Same was not working if i convert it to string using toUriString

Below is the code which worked for me.

URI uri = UriComponentsBuilder.fromUriString(uri)
                              .queryParam("filter",encodedParam)
                              .encode()
                              .build()
                              .toUri();

restTemplate.exchange(uri, HttpMethod.GET, request, Response_Entity.class)

Upvotes: 0

Marc Stroebel
Marc Stroebel

Reputation: 2357

try encoding query param by using URLEncoder.

String param = "IN('123') and id eq '123_&123'";
String encodedParam = URLEncoder.encode(param, Charset.defaultCharset()));    
restTemplate.exchange(UriComponentsBuilder.fromUriString(uri).queryParam("filter",encodedParam).toUriString(), httpMethod, httpEntity, Some_Entity.class)

https://www.baeldung.com/java-url-encoding-decoding

Upvotes: 2

Related Questions