Paul Draper
Paul Draper

Reputation: 83323

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.

Upvotes: 10

Views: 12484

Answers (2)

electrobabe
electrobabe

Reputation: 1647

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) {
  ..
}

Upvotes: 9

Petr Janeček
Petr Janeček

Reputation: 38444

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.

Upvotes: 8

Related Questions