【问题标题】:How to do URL decoding in Java?如何在 Java 中进行 URL 解码?
【发布时间】:2011-09-02 13:07:36
【问题描述】:

在 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 格式叫什么?如何转换它们?

【问题讨论】:

  • @Stephen .. 为什么 url 不能是 UTF-8 编码的字符串 .. ?
  • 问题在于,仅仅因为 URL 可以是 UTF-8,这个问题确实与 UTF-8 无关。我已经适当地编辑了这个问题。
  • 可能是(理论上),但您示例中的字符串不是 UTF-8 编码的字符串。它是一个 URL 编码的 ASCII 字符串。因此,标题具有误导性。
  • 另外值得注意的是,url字符串中的所有字符都是ASCII,在字符串经过URL解码后也是如此。如果xx 小于(十六进制)80'%' 是一个 ASCII 字符,%xx 表示一个 ASCII 字符。

标签: java url-encoding


【解决方案1】:

这与 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

【讨论】:

  • URLDecoder 上的方法是静态的,因此您不必创建它的新实例。
  • @Trismegistos 根据 Java 7 API 文档,仅不推荐使用未指定字符编码的版本(第二个参数 "UTF-8")。使用带有两个参数的版本。
  • 如果使用 java 1.7+,您可以使用此包中的“UTF-8”字符串的静态版本:StandardCharsets.UTF_8.name()java.nio.charset.StandardCharsets。与此相关:link
  • 对于字符编码,这也是一篇很棒的文章 balusc.blogspot.in/2009/05/unicode-how-to-get-characters-right.html
  • 小心这个。如此处所述:blog.lunatech.com/2009/02/03/… 这与 URL 无关,而是用于 HTML 表单编码。
【解决方案2】:

你得到的字符串是application/x-www-form-urlencoded编码的。

使用URLDecoder 将其转换为Java 字符串。

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

【讨论】:

    【解决方案3】:

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

    “您应该使用 java.net.URI 来执行此操作,因为 URLDecoder 类执行 x-www-form-urlencoded 解码,这是错误的(尽管名称如此,但它用于表单数据)。”

    正如URL 类文档所述:

    管理 URL 编码和解码的推荐方法是 使用URI,并使用toURI() 和在这两个类之间进行转换 URI.toURL().

    URLEncoderURLDecoder 类也可以使用,但仅限于 HTML表单编码,与编码方案不一样 在RFC2396中定义。

    基本上:

    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
    

    【讨论】:

    • 在 Java 1.7 中,URLDecoder.decode(String, String) 重载未被弃用。您必须引用没有编码的URLDecoder.decode(String) 重载。您可能需要更新您的帖子以进行澄清。
    • 这个答案具有误导性;该块引用与弃用无关。已弃用方法的 Javadoc 声明,我实际上引用了@deprecated The resulting string may vary depending on the platform's default encoding. Instead, use the decode(String,String) method to specify the encoding.
    • URI 的 getPath() 仅返回 URI 的路径部分,如上所述。
    • 除非我弄错了,否则已知“路径”是 URI 的授权部分之后的部分(参见:en.wikipedia.org/wiki/Uniform_Resource_Identifier 路径的定义) - 在我看来,我的行为我看到的是标准/正确的行为。我正在使用 java 1.8.0_101(在 Android Studio 上)。我很想知道您在调用“getAuthority()”时会得到什么。甚至这篇文章/示例似乎也表明路径只是其 URI 的 /public/manual/appliances 部分:quepublishing.com/articles/article.aspx?p=26566&seqNum=3
    • @Pelpotronic 帖子中的代码实际上确实打印了它显示的输出(至少对我而言)。我认为这样做的原因是,由于 URL 编码,URI 构造函数实际上将整个字符串 (https%3A%2F...) 视为 URI 的路径;没有权限,或者查询等。这可以通过在URI对象上调用相应的get方法来测试。如果将解码后的文本传递给 URI 构造函数:new URI("https://mywebsite/do....."),那么调用getPath() 等方法将给出正确的结果。
    【解决方案4】:

    %3A%2F 是 URL 编码字符。使用此 java 代码将它们转换回 :/

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

    【讨论】:

    【解决方案5】:
     try {
            String result = URLDecoder.decode(urlString, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    【讨论】:

      【解决方案6】:
      public String decodeString(String URL)
          {
      
          String urlString="";
          try {
              urlString = URLDecoder.decode(URL,"UTF-8");
              } catch (UnsupportedEncodingException e) {
                  // TODO Auto-generated catch block
      
              }
      
              return urlString;
      
          }
      

      【讨论】:

      • 能否请您详细说明您的答案,添加更多关于您提供的解决方案的描述?
      【解决方案7】:

      我用apache commons

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

      默认字符集是UTF-8

      【讨论】:

        【解决方案8】:
        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")); 
        
            } 
        
        }
        

        你可以明智地选择你的方法:)

        【讨论】:

          【解决方案9】:

          使用 java.net.URI 类:

          public String getDecodedURL(String encodedUrl) {
              try {
                  URI uri = new URI(encodedUrl);
                  return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
              } catch (Exception e) {
                  return "";
              }
          }
          

          请注意,异常处理可能会更好,但与本示例关系不大。

          【讨论】:

            【解决方案10】:

            如果是整数值,我们也要捕获 NumberFormatException。

            try {
                    Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
                } catch (NumberFormatException | UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            

            【讨论】:

              猜你喜欢
              • 2015-01-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多