Java equivalent to JavaScript's encodeURIComponent that produces identical output?
我一直在尝试各种Java代码,试图提供一些东西来对包含引号,空格和"奇异" Unicode字符的字符串进行编码,并产生与JavaScript的encodeURIComponent函数相同的输出。
我的酷刑测试字符串是:" A" B±"
如果我在Firebug中输入以下JavaScript语句:
1 | encodeURIComponent('"A" B ±"'); |
然后我得到:
1 | "%22A%22%20B%20%C2%B1%20%22" |
这是我的小测试Java程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class EncodingTest { public static void main(String[] args) throws UnsupportedEncodingException { String s =""A" B ± ""; System.out.println("URLEncoder.encode returns" + URLEncoder.encode(s,"UTF-8")); System.out.println("getBytes returns" + new String(s.getBytes("UTF-8"),"ISO-8859-1")); } } |
该程序输出:
1 2 |
靠近,但没有雪茄! 使用Java编码UTF-8字符串以使其产生与JavaScript的
编辑:我正在使用Java 1.4即将移至Java 5。
这是我最后提出的课程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; /** * Utility class for JavaScript compatible UTF-8 encoding and decoding. * * @see http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output * @author John Topley */ public class EncodingUtil { /** * Decodes the passed UTF-8 String using an algorithm that's compatible with * JavaScript's <wyn>decodeURIComponent</wyn> function. Returns * <wyn>null</wyn> if the String is <wyn>null</wyn>. * * @param s The UTF-8 encoded String to be decoded * @return the decoded String */ public static String decodeURIComponent(String s) { if (s == null) { return null; } String result = null; try { result = URLDecoder.decode(s,"UTF-8"); } // This exception should never occur. catch (UnsupportedEncodingException e) { result = s; } return result; } /** * Encodes the passed String as UTF-8 using an algorithm that's compatible * with JavaScript's <wyn>encodeURIComponent</wyn> function. Returns * <wyn>null</wyn> if the String is <wyn>null</wyn>. * * @param s The String to be encoded * @return the encoded String */ public static String encodeURIComponent(String s) { String result = null; try { result = URLEncoder.encode(s,"UTF-8") .replaceAll("\\+","%20") .replaceAll("\\%21","!") .replaceAll("\\%27","'") .replaceAll("\\%28","(") .replaceAll("\\%29",")") .replaceAll("\\%7E","~"); } // This exception should never occur. catch (UnsupportedEncodingException e) { result = s; } return result; } /** * Private constructor to prevent this class from being instantiated. */ private EncodingUtil() { super(); } } |
查看实现差异,我发现:
-
文字字符(正则表达式表示):
[-a-zA-Z0-9._*~'()!]
-
文字字符(正则表达式表示):
[-a-zA-Z0-9._*] -
空格字符
"" 转换为加号"+" 。
因此,基本上,要获得所需的结果,请使用
-
用
"%20" 替换所有出现的"+" -
将代表
[~'()!] 中任何一个的"%xx" 的所有出现替换回其文字对应部分
使用Java 6随附的javascript引擎:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <wyn> import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Wow { public static void main(String[] args) throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval("print(encodeURIComponent('"A" B ± "'))"); } } </wyn> |
输出:%22A%22%20B%20%c2%b1%20%22
情况不同,但更接近您想要的。
我使用
后处理
1 |
将为您提供
我想出了自己的encodeURIComponent版本,因为发布的解决方案存在一个问题,如果String中存在+,应该对其进行编码,它将转换为空格。
所以这是我的课:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import java.io.UnsupportedEncodingException; import java.util.BitSet; public final class EscapeUtils { /** used for the encodeURIComponent function */ private static final BitSet dontNeedEncoding; static { dontNeedEncoding = new BitSet(256); // a-z for (int i = 97; i <= 122; ++i) { dontNeedEncoding.set(i); } // A-Z for (int i = 65; i <= 90; ++i) { dontNeedEncoding.set(i); } // 0-9 for (int i = 48; i <= 57; ++i) { dontNeedEncoding.set(i); } // '()* for (int i = 39; i <= 42; ++i) { dontNeedEncoding.set(i); } dontNeedEncoding.set(33); // ! dontNeedEncoding.set(45); // - dontNeedEncoding.set(46); // . dontNeedEncoding.set(95); // _ dontNeedEncoding.set(126); // ~ } /** * A Utility class should not be instantiated. */ private EscapeUtils() { } /** * Escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( ) * * @param input * A component of a URI * @return the escaped URI component */ public static String encodeURIComponent(String input) { if (input == null) { return input; } StringBuilder filtered = new StringBuilder(input.length()); char c; for (int i = 0; i < input.length(); ++i) { c = input.charAt(i); if (dontNeedEncoding.get(c)) { filtered.append(c); } else { final byte[] b = charToBytesUTF(c); for (int j = 0; j < b.length; ++j) { filtered.append('%'); filtered.append("0123456789ABCDEF".charAt(b[j] >> 4 & 0xF)); filtered.append("0123456789ABCDEF".charAt(b[j] & 0xF)); } } } return filtered.toString(); } private static byte[] charToBytesUTF(char c) { try { return new String(new char[] { c }).getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { return new byte[] { (byte) c }; } } } |
我想出了另一个实现方法,该实现方法记录在http://blog.sangupta.com/2010/05/encodeuricomponent-and.html。该实现还可以处理Unicode字节。
这就是我正在使用的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | private static final String HEX ="0123456789ABCDEF"; public static String encodeURIComponent(String str) { if (str == null) return null; byte[] bytes = str.getBytes(StandardCharsets.UTF_8); StringBuilder builder = new StringBuilder(bytes.length); for (byte c : bytes) { if (c >= 'a' ? c <= 'z' || c == '~' : c >= 'A' ? c <= 'Z' || c == '_' : c >= '0' ? c <= '9' : c == '-' || c == '.') builder.append((char)c); else builder.append('%') .append(HEX.charAt(c >> 4 & 0xf)) .append(HEX.charAt(c & 0xf)); } return builder.toString(); } |
根据RFC 3986的规定,它对每个不是非保留字符的字符进行百分比编码,从而超越了Javascript。
这是相反的转换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public static String decodeURIComponent(String str) { if (str == null) return null; int length = str.length(); byte[] bytes = new byte[length / 3]; StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length; ) { char c = str.charAt(i); if (c != '%') { builder.append(c); i += 1; } else { int j = 0; do { char h = str.charAt(i + 1); char l = str.charAt(i + 2); i += 3; h -= '0'; if (h >= 10) { h |= ' '; h -= 'a' - '0'; if (h >= 6) throw new IllegalArgumentException(); h += 10; } l -= '0'; if (l >= 10) { l |= ' '; l -= 'a' - '0'; if (l >= 6) throw new IllegalArgumentException(); l += 10; } bytes[j++] = (byte)(h << 4 | l); if (i >= length) break; c = str.charAt(i); } while (c == '%'); builder.append(new String(bytes, 0, j, UTF_8)); } } return builder.toString(); } |
这是Ravi Wallau解决方案的简单示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public String buildSafeURL(String partialURL, String documentName) throws ScriptException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager .getEngineByName("JavaScript"); String urlSafeDocumentName = String.valueOf(scriptEngine .eval("encodeURIComponent('" + documentName +"')")); String safeURL = partialURL + urlSafeDocumentName; return safeURL; } public static void main(String[] args) { EncodeURIComponentDemo demo = new EncodeURIComponentDemo(); String partialURL ="https://www.website.com/document/"; String documentName ="Tom & Jerry Manuscript.pdf"; try { System.out.println(demo.buildSafeURL(partialURL, documentName)); } catch (ScriptException se) { se.printStackTrace(); } } |
输出:
它还回答了Loren Shqipognja的注释中有关如何将String变量传递给
我用了
编码网址。
要在
对我来说,这工作:
1 2 3 4 5 6 7 | import org.apache.http.client.utils.URIBuilder; String encodedString = new URIBuilder() .setParameter("i", stringToEncode) .build() .getRawQuery() // output: i=encodedString .substring(2); |
或使用其他UriBuilder
1 2 3 4 5 6 | import javax.ws.rs.core.UriBuilder; String encodedString = UriBuilder.fromPath("") .queryParam("i", stringToEncode) .toString() // output: ?i=encodedString .substring(3); |
我认为使用标准库比手动进行后期处理更好。另外@Chris回答看起来不错,但不适用于网址,例如" http:// a + b c.html"
番石榴库具有PercentEscaper:
" -_。*"是安全字符
false表示PercentEscaper使用'%20'而不是'+'转义空间
我已经成功使用了java.net.URI类,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static String uriEncode(String string) { String result = string; if (null != string) { try { String scheme = null; String ssp = string; int es = string.indexOf(':'); if (es > 0) { scheme = string.substring(0, es); ssp = string.substring(es + 1); } result = (new URI(scheme, ssp, null)).toString(); } catch (URISyntaxException usex) { // ignore and use string that has syntax error } } return result; } |
我已经从google-http-java-client库中找到了PercentEscaper类,可以很容易地实现它。
来自Google-http-java-client javadoc的PercentEscaper
google-http-java-client主页