Spring Web: Encode ‘+’ Value Using UriComponentsBuilder

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

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s