在 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 向 API 添加了对 Charset
的直接支持,这意味着无需捕获 UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
请注意,字符编码(例如 UTF-8 或 ASCII)决定了字符到原始字节的映射。有关字符编码的详细介绍,请参阅 this article .
https://stackoverflow.com/questions/6138127/