Search code examples
javaurlencodespring-resttemplate

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 ?


Solution

  • 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)