一尘不染

如何用Java进行URL解码?

java

在Java中,我想将其转换为:

https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type

对此:

https://mywebsite/docs/english/site/mybook.do&request_type

这是我到目前为止所拥有的:

class StringUTF 
{
    public static void main(String[] args) 
    {
        try{
            String url = 
               "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
               "%3Frequest_type%3D%26type%3Dprivate";

            System.out.println(url+"Hello World!------->" +
                new String(url.getBytes("UTF-8"),"ASCII"));
        }
        catch(Exception E){
        }
    }
}

但这行不通。这些%3A和%2F格式分别是什么?如何转换它们?


阅读 472

收藏
2020-02-29

共1个答案

一尘不染

这与字符编码(例如UTF-8或ASCII)无关。你所拥有的字符串已进行URL编码。这种编码与字符编码完全不同。

尝试这样的事情:

try {
    String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
    // not going to happen - value came from JDK's own StandardCharsets
}
Java 10 Charset为该API 添加了直接支持,这意味着无需捕获UnsupportedEncodingException:

String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);

请注意,字符编码(例如UTF-8或ASCII)决定了字符到原始字节的映射。

2020-02-29