如何在 Java 中进行 URL 解码? [英] How to do URL decoding in 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
格式是什么,我该如何转换它们?
But it doesn't work right. What are these %3A
and %2F
formats called and how do I convert them?
推荐答案
这与 UTF-8 或 ASCII 等字符编码没有任何关系.您拥有的字符串是URL 编码.这种编码与字符编码完全不同.
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
试试这样的:
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 为 API 添加了对 Charset
的直接支持,这意味着无需捕获 UnsupportedEncodingException:
Java 10 added direct support for Charset
to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
请注意,字符编码(例如 UTF-8 或 ASCII)决定了字符到原始字节的映射.有关字符编码的详细介绍,请参阅这篇文章.
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
这篇关于如何在 Java 中进行 URL 解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!