Java编程语言中是否有与JavaScript unescape函数等效的函数?也就是说,如果我的输入是字符串“I%20need%20help%21”,则输出必须是“我需要帮助!”,例如。
谢谢!
答案 0 :(得分:8)
如果编码字符串中存在非ASCII字符,根据我的经验URLDecoder.decode
可能会失败。例如这段代码:
URLDecoder.decode("%u017C", "UTF-8"); // %u017C is the result of running in Javascript escape('ż')
抛出以下异常:
Exception in thread "main" java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u0"
我所知道的解决这个问题的最佳方法(虽然笨拙)只是在Java中运行Javascript :(
String jsEscapedString = "%u017C";
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
String result = (String) engine.eval("unescape('" + jsEscapedString + "')");
启发的BTW解决方案
答案 1 :(得分:4)
您可以使用URLDecoder
。假设您使用的是UTF-8:
String result = URLDecoder.decode(s, "UTF-8");
答案 2 :(得分:1)
试试这个
URLDecoder dec = new URLDecoder();
String val = dec.decode("I%20need%20help%21","UTF-8");
System.out.println(val);
答案 3 :(得分:0)
这很好@Nrj,但开发人员要静态调用它。
URLDecoder.decode("I%20need%20help%21","UTF-8");