如何用Java编码百分比?

Pau*_*per 5 java percent-encoding

RFC 3986中所述,如何对字符串进行百分比编码?即我不想(IMO,怪异)www-url-form-encoded,因为 不同的.

如果重要,我编码的数据不一定是整个URL.

ele*_*abe 7

Guava的 com.google.common.net.PercentEscaper (标记为“Beta”,因此不稳定):

UnicodeEscaper basicEscaper = new PercentEscaper("-", false);
String s = basicEscaper.escape(s);
Run Code Online (Sandbox Code Playgroud)

java.net.URLEncoder的解决方法:

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


Pet*_*ček 5

如您所知,标准库无法很好地解决该问题。

根据您要编码的URL的哪一部分,尝试使用Guava的PercentEscaper,或直接使用其中的URL逸出器