How to percent encode in Java?

11.1k views Asked by At

How do I do percent encoding of a string, as described in RFC 3986? I.e. I do not want (IMO, weird) www-url-form-encoded, as that is different.

If it matters, I am encoding data that is not necessarily an entire URL.

2

There are 2 answers

3
Petr Janeček On

As you have identified, the standard libraries don't cope very well with the problem.

Try to use either Guava's PercentEscaper, or directly one of the URL escapers depending on which part of the URL you're trying to encode.

1
electrobabe On

Guava's com.google.common.net.PercentEscaper (marked "Beta" and therefore unstable):

UnicodeEscaper basicEscaper = new PercentEscaper("-", false);
String s = basicEscaper.escape(s);

Workaround with java.net.URLEncoder:

try {
  String s = URLEncoder.encode(s, "UTF-8").replace("+", "%20");
} catch (UnsupportedEncodingException e) {
  ..
}