Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to percent encode in Java?

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.

like image 857
Paul Draper Avatar asked Dec 01 '14 00:12

Paul Draper


People also ask

How do you calculate percent encoding in Java?

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

How do I encode a percentage?

Percent-encoding is a mechanism to encode 8-bit characters that have specific meaning in the context of URLs. It is sometimes called URL encoding. The encoding consists of substitution: A '%' followed by the hexadecimal representation of the ASCII value of the replace character.


2 Answers

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.

like image 144
Petr Janeček Avatar answered Oct 07 '22 11:10

Petr Janeček


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) {
  ..
}
like image 24
electrobabe Avatar answered Oct 07 '22 09:10

electrobabe