如何在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)没有任何关系。 你在那里的string是URL编码 。 这种编码与字符编码完全不同。

尝试这样的事情:

 String result = java.net.URLDecoder.decode(url, "UTF-8"); 

请注意, 字符编码 (例如UTF-8或ASCII)决定了字符到原始字节的映射。 对于字符编码的一个很好的介绍,请参阅这篇文章 。

你得到的string是application/x-www-form-urlencoded编码。

使用URLDecoder将其转换为Java String。

 URLDecoder.decode( url, "UTF-8" ); 

这已经被回答(虽然这个问题是第一!):

“你应该使用java.net.URI来做到这一点,因为URLDecoder类的x-www-form-urlencoded解码是错误的(尽pipe名称是表单数据)。

基本上:

 String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"; System.out.println(new java.net.URI(url).getPath()); 

会给你:

 https://mywebsite/docs/english/site/mybook.do?request_type 

%3A%2F是URL编码的字符。 使用这个Java代码将它们转换回:/

 String decoded = java.net.URLDecoder.decode(url, "UTF-8"); 
  try { String result = URLDecoder.decode(urlString, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

我使用Apache的公共

 String decodedUrl = new URLCodec().decode(url); 

默认字符集是UTF-8

 public String decodeString(String URL) { String urlString=""; try { urlString = URLDecoder.decode(URL,"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block } return urlString; } 
 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")); } } 

你可以明智地select你的方法:)