9

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.

Community
  • 1
  • 1
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • This do it for you?https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html. Woops, didnt read properly. Ignore – Zack Newsham Dec 01 '14 at 01:00
  • @ZackNewsham, no, as that uses www-url-form-encoded. – Paul Draper Dec 01 '14 at 01:00
  • Could you define "standard"? Does it have to encode spaces in the URL as `%20`, and spaces in the query string as `+`? What about other special characters? – tckmn Dec 01 '14 at 01:01
  • 1
    ok, here you go: http://stackoverflow.com/questions/4737841/urlencoder-not-able-to-translate-space-character – Zack Newsham Dec 01 '14 at 01:01
  • Does Guava's [`PercentEscaper`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/net/PercentEscaper.html) work for you? Or, rather, one of [the URL escapers](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/net/UrlEscapers.html)? – Petr Janeček Dec 01 '14 at 01:03
  • @Slanec and Zack yes, those work. – Paul Draper Dec 01 '14 at 01:05
  • Does this answer your question? [Java URL encoding of query string parameters](https://stackoverflow.com/questions/10786042/java-url-encoding-of-query-string-parameters) – fireball.1 Apr 21 '21 at 18:10

2 Answers2

7

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.

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
6

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) {
  ..
}
electrobabe
  • 1,549
  • 18
  • 17