简体   繁体   中英

URLDecoder.decode(encodedString, “UTF-8”) alternative

URLDecoder.decode throws UnsupportedEncodingException .

Is there any other way to achieve decoding, without handling this exception?

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
}

Output:

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

You can use Apache commons URLCodec :

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

According to the docs:

This codec is meant to be a replacement for standard Java classes URLEncoder and URLDecoder on older Java platforms, as these classes in Java versions below 1.4 rely on the platform's default charset encoding.

You still have to handle the DecoderException though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM