Search code examples
springspring-booturl-encodingspring-restspring-web

Spring boot 2: Plus (+) sign is not getting encoded in query param


Currently I am migrating one of my micro service to spring boot 2 from spring boot 1.x. consider there are two services A and B. Service A calls the rest end point of service B. In query Param service A is passing an alphanumeric string which also contains (+) character ( not always as it's a random generated string). Service B compares this string with the one stored in db and returns the response.

I observed that with version 1.x URL is getting encoded properly. Ex. If I pass (a+b) it gets encoded as a%2Bb and in service B it gets decoded as (a+b). However, with version 2.x it gets encoded as (a+b) only and as a result in service B it gets decoded as (a b) [+ gets decoded to white space]

I am using UriComponentBuilder to build the URI and encode() method for encoding the URI. While debugging I found that + character is allowed in URL and that's the reason it doesn't get encoded.

My question is - Is there a way to change this behaviour so that I get + as %2B . Or, kindly point me to right place, if I am doing something wrong. I can share the code as well if needed.


Solution

  • From the spring docs and from this issue you have to "invoke encode before and not after expanding URI variables". E.G.

    .encode()
    .buildAndExpand("New York", "foo+bar")
    

    In response to the comment:

    If + character is allowed in URL then why does it get decoded as white space rather than the + character itself

    From w3schools:

    URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.