Embracing the Messiness in Search of Epic Solutions

Spring Web: Encode ‘+’ Value Using UriComponentsBuilder

Posted

in

PROBLEM

Given the following code…

final String url = UriComponentsBuilder.
        fromHttpUrl('https://server').
        queryParam('var', '{var}').
        buildAndExpand('1 2+3').
        encode().
        toString()


When using Spring Web 4.3.18.RELEASE, the URL is properly encoded:-

https://server?var=1%202%2B3


However, when using version between 5.0.0.RELEASE and 5.0.7.RELEASE, the URL containing “+” value does not get encoded:-

https://server?var=1%202+3

SOLUTION

There is a ticket opened regarding this breaking change.

To properly encode “+” value, use 5.0.8.RELEASE or later.

Then, ensure encode() is invoked before buildAndExpand(..):-

// Produces https://server?var=1%202%2B3
final String url = UriComponentsBuilder.
        fromHttpUrl('https://server').
        queryParam('var', '{var}').
        encode().
        buildAndExpand('1 2+3').
        toString()


The above code can be further shorten to this:-

// Produces https://server?var=1%202%2B3
final String url = UriComponentsBuilder.
        fromHttpUrl('https://server').
        queryParam('var', '{var}').
        build('1 2+3').
        toString()

Tags:

Comments

One response to “Spring Web: Encode ‘+’ Value Using UriComponentsBuilder”

  1. Amit Avatar
    Amit

    The solution worked perfectly well for me. Thank you!

Leave a Reply