How do I encode URI parameter values?

127,536

Solution 1

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

Solution 2

You could also use Spring's UriUtils

Solution 3

I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey).

Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime.

Solution 4

I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/

Solution 5

It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.

Share:
127,536
Gili
Author by

Gili

Email: cowwoc2020 at gmail dot com.

Updated on April 12, 2020

Comments

  • Gili
    Gili about 4 years

    I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:

    http://google.com/resource?key=value1 & value2

    I expect the output:

    http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2

    Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.