Java相当于JavaScript的encodeURIComponent,产生相同的输出?

2022-08-31 09:40:59

我一直在尝试各种Java代码,试图想出一些东西来编码包含引号,空格和“异国情调”Unicode字符的字符串,并产生与JavaScript的codeURIComponent函数相同的输出。

我的酷刑测试字符串是:“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+%22
getBytes returns "A" B ± "

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

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


答案 1

这是我最后想出的类:

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();
  }
}

答案 2

查看实现差异,我发现:

MDC on encodeURIComponent()

  • 文字字符(正则表达式表示形式):[-a-zA-Z0-9._*~'()!]

关于 URLEncoder 的 Java 1.5.0 文档

  • 文字字符(正则表达式表示形式):[-a-zA-Z0-9._*]
  • 空格字符将转换为加号 。" ""+"

因此,基本上,要获得所需的结果,请使用然后进行一些后处理:URLEncoder.encode(s, "UTF-8")

  • 将所有出现的 替换为"+""%20"
  • 替换所有出现的表示任何的返回到其文字对应部分"%xx"[~'()!]