gpt4 book ai didi

Java 等效于产生相同输出的 JavaScript 的 encodeURIComponent?

转载 作者:IT老高 更新时间:2023-10-28 11:38:57 25 4
gpt4 key购买 nike

我一直在尝试各种 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 returns %22A%22+B+%C2%B1+%22getBytes returns "A" B ± "

关闭,但没有雪茄!使用 Java 对 UTF-8 字符串进行编码以使其产生与 JavaScript 的 encodeURIComponent 相同的输出的最佳方法是什么?

编辑:我正在使用 Java 1.4,很快就会迁移到 Java 5。

最佳答案

这是我最后想出的类(class):

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 等效于产生相同输出的 JavaScript 的 encodeURIComponent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/607176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com