Java相当于JavaScript的encodeURIComponent产生相同的输出?
我一直在尝试各种各样的Java代码试图想出一些东西,将编码包含引号,空格和“异国情调”的Unicode字符的string,并产生与JavaScript的encodeURIComponent函数相同的输出。
我的酷刑testingstring是: “A”B±“
如果我在Firebug中input以下JavaScript语句:
encodeURIComponent('"A" B ± "');
– 那么我得到:
"%22A%22%20B%20%C2%B1%20%22"
这是我的小testingJava程序:
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")); } }
这个程序输出:
URLEncoder.encode返回%22A%22 + B +%C2%B1 +%22 getBytes返回“A”B±“
closures,但没有雪茄! 使用Java对UTF-8string进行编码的最佳方法是什么,以便它产生与JavaScript的encodeURIComponent
相同的输出?
编辑:我正在使用Java 1.4移动到Java 5很快。
从实施的差异来看,我看到:
encodeURIComponent()
上的MDC :
- 文字字符(正则expression式):
[-a-zA-Z0-9._*~'()!]
关于URLEncoder
Java 1.5.0文档 :
- 文字字符(正则expression式):
[-a-zA-Z0-9._*]
- 空格字符
" "
被转换成加号"+"
。
所以基本上,为了得到所需的结果,使用URLEncoder.encode(s, "UTF-8")
,然后做一些后处理:
- 将所有出现的
"+"
replace为"%20"
- 将代表任何
[~'()!]
所有"%xx"
replace回它们的文字相对部分
这是我最后提出的课程:
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 <code>decodeURIComponent</code> function. Returns * <code>null</code> if the String is <code>null</code>. * * @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 <code>encodeURIComponent</code> function. Returns * <code>null</code> if the String is <code>null</code>. * * @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(); } }
使用Java 6附带的JavaScript引擎:
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 ± \"'))"); } }
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 ± \"'))"); } }
产出:%22A%22%20B%20%c2%b1%20%22
案件是不同的,但它更接近你想要的。
我使用java.net.URI#getRawPath()
,例如
String s = "a+b c.html"; String fixed = new URI(null, null, s, null).getRawPath();
fixed
的价值将是a+b%20c.html
,这是你想要的。
后处理URLEncoder.encode()
的输出将删除应该在URI中的任何加号。 例如
URLEncoder.encode("a+b c.html").replaceAll("\\+", "%20");
会给你a%20b%20c.html
,这将被解释为ab c.html
。
我想出了自己的encodeURIComponent版本,因为发布的解决scheme有一个问题,如果在string中存在+应该被编码,它将被转换为空格。
所以这是我的class级:
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); // az for (int i = 97; i <= 122; ++i) { dontNeedEncoding.set(i); } // AZ 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字节。
我从google-http-java-client库中find了PercentEscaper类,它可以很容易地用来实现encodeURIComponent。
google-http-java-client javadoc google-http-java-client home
我已经成功地使用java.net.URI类如下所示:
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; }
这是一个简单的例子Ravi Wallau的解决scheme:
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(); } }
输出: https://www.website.com/document/Tom%20%26%20Jerry%20Manuscript.pdf
: https://www.website.com/document/Tom%20%26%20Jerry%20Manuscript.pdf
它还回答了Loren Shqipognja在如何将一个Stringvariables传递给encodeURIComponent()
的评论中的悬而未决的问题。 scriptEngine.eval()
方法返回一个Object
,所以它可以通过String.valueOf()
等方法转换为String。
对我来说这工作:
import org.apache.http.client.utils.URIBuilder; String encodedString = new URIBuilder() .setParameter("i", stringToEncode) .build() .getRawQuery() // output: i=encodedString .substring(2);
或与不同的UriBuilder
import javax.ws.rs.core.UriBuilder; String encodedString = UriBuilder.fromPath("") .queryParam("i", stringToEncode) .toString() // output: ?i=encodedString .substring(3);
在我看来,使用标准库是一个更好的主意,而不是手动后处理。 @Chris答案看起来不错,但它不适用于url,如“ http:// a + b c.html”
番石榴图书馆有PercentEscaper:
Escaper percentEscaper = new PercentEscaper("-_.*", false);
“-_。*”是安全的字符
false表示PercentEscaper用'%20'来跳过空格,而不是'+'