如何用Java进行URL解码?
在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格式分别是什么?如何转换它们?
回答:
这与字符编码(例如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)决定了字符到原始字节的映射。
以上是 如何用Java进行URL解码? 的全部内容, 来源链接: utcz.com/qa/412052.html