本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
问题:如何在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在API中添加了对字符集的直接支持,这意味着不需要捕获UnsupportedEncodingException
异常了
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
复制代码
回答二
你应该使用java.net.URI
来执行此操作,因为urldecker
类是解码x-www-form-urlencoded
的,它是针对表单数据的。
正如URL
文档所述
管理URL
编码和解码的推荐方法是使用URI。并使用toURI()
和URI.toURL()
进行类之间的转换。
示例
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
复制代码
回答三
这是我写的URL解码器:
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
复制代码
文章翻译自Stack Overflow:stackoverflow.com/questions/6…
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END