cra*_*ace 311 java url-encoding
在Java中,我想转换它:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
Run Code Online (Sandbox Code Playgroud)
对此:
https://mywebsite/docs/english/site/mybook.do&request_type
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止:
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){
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它不能正常工作.这些%3A和%2F格式被称为什么以及如何转换它们?
Jes*_*per 615
这与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
}
Run Code Online (Sandbox Code Playgroud)
Java 10增加Charset了对API的直接支持,这意味着不需要捕获UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)
请注意,字符编码(例如UTF-8或ASCII)决定了字符到原始字节的映射.有关字符编码的详细介绍,请参阅此文章.
Ale*_*yak 50
你得到的字符串是application/x-www-form-urlencoded编码.
使用URLDecoder将其转换为Java String.
URLDecoder.decode( url, "UTF-8" );
Run Code Online (Sandbox Code Playgroud)
Nic*_*aly 45
"您应该使用java.net.URI来执行此操作,因为URLDecoder类执行x-www-form-urlencoded解码是错误的(尽管名称,它是表单数据)."
基本上:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
Run Code Online (Sandbox Code Playgroud)
会给你:
https://mywebsite/docs/english/site/mybook.do?request_type
Run Code Online (Sandbox Code Playgroud)
laz*_*laz 14
%3A并且%2F是URL编码的字符.使用此java代码将它们转换回:和/
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
Run Code Online (Sandbox Code Playgroud)
我使用阿帕奇公共资源
String decodedUrl = new URLCodec().decode(url);
Run Code Online (Sandbox Code Playgroud)
默认字符集是UTF-8
小智 5
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
Run Code Online (Sandbox Code Playgroud)