URLDecoder.decode(encodedString," UTF-8")替代

时间:2017-09-14 06:27:54

标签: java

URLDecoder.decode抛出UnsupportedEncodingException

有没有其他方法可以实现解码,而不处理此异常?

public static void main(String[] args) throws UnsupportedEncodingException {
    String encodedString = "Testing some character I want to claim %C2%A3300.00 I want to claim %24400.00 I want to claim %E2%82%AC500.00";
    System.out.println( URLDecoder.decode(encodedString, "UTF-8"));
    byte[] bytes = encodedString.getBytes("UTF-8");
    String s2 = new String(bytes, "UTF-8");
    System.out.println(s2); //doesnt work
    String decoded = new String(encodedString.getBytes("ISO-8859-1"));
    System.out.println(decoded); //doesnt work
}

输出:

Testing some character I want to claim £300.00 I want to claim $400.00 I want to claim €500.00
Testing some character I want to claim %C2%A3300.00 I want to claim %24400.00 I want to claim %E2%82%AC500.00
Testing some character I want to claim %C2%A3300.00 I want to claim %24400.00 I want to claim %E2%82%AC500.00

1 个答案:

答案 0 :(得分:2)

您可以使用Apache commons URLCodec

String decoded = new URLCodec().decode(encodedString);

根据文件:

  

此编解码器旨在替代旧Java平台上的标准Java类URLEncoder和URLDecoder,因为1.4版以下的Java版本中的这些类依赖于平台的默认字符集编码。

你仍然需要处理DecoderException