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.
try { String s = URLEncoder. encode(s, "UTF-8"). replace("+", "%20"); } catch (UnsupportedEncodingException e) { .. }
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.
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.
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) {
..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With