我一直在尝试各种各样的Java代码,尝试提出一些将编码包含引号,空格和“异国情调”的Unicode字符的字符串,并生成与JavaScript的encodeURIComponent函数相同的输出。
我的酷刑测试字符串是:“A”B±“
如果我在Firebug中输入以下JavaScript语句:
encodeURIComponent('"A" B ± "');
- 然后我得到:
"%22A%22%20B%20%C2%B1%20%22"
这是我的小测试Java程序:
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±“
关闭,但没有雪茄!使用Java对UTF-8字符串进行编码的最佳方式是什么,以便它产生与JavaScript相同的输出encodeURIComponent
?
我正在使用Java 1.4移动到Java 5很快。
发布于 2018-03-06 12:50:17
从执行方面的差异来看,我看到:
转换为
加号...
因此,基本上,要获得所需的结果,请使用然后做一些后处理:
带着
代表回到他
们字面上
的对立面发布于 2018-03-06 14:22:52
这是我最后提出的课程:
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();
}
}
https://stackoverflow.com/questions/-100007523
复制相似问题