4

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.

Sachin
  • 521
  • 3
  • 11

1 Answers1

3

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.

Robert Bain
  • 9,113
  • 8
  • 44
  • 63
  • 1
    I am still thinking about one point. If + character is allowed in URL then why does it get decoded as white space rather than the + character itself. If you can answer. Thanks. – Sachin Mar 13 '19 at 09:32
  • @Sachin I think that's the real problem. If it at least did the same for encoding and decoding URLs, that would be one thing. But it's internally inconsistent: Spring MVC Controllers replace plus signs with spaces when decoding the request parameters (or perhaps it's the embedded Tomcat that does this), but when encoding URLs with `UrlComponentBuilder`, it doesn't encode the plus signs as `%2b` to make sure they don't get interpreted as encoded spaces. – Frans Mar 13 '23 at 07:48
  • OK, that's basically what it says here: https://stackoverflow.com/questions/50270372/why-is-spring-de-coding-the-plus-character-on-application-json-get-requests – Frans Mar 13 '23 at 07:53