【问题标题】:How to avoid redundant double encoding in java.net.URI?如何避免 java.net.URI 中的冗余双重编码?
【发布时间】:2015-05-16 02:06:38
【问题描述】:

我正在编写一个从 URL 到 URI 的转换,用于只接受 java.net.URI 作为参数的 Http 方法。

我的实现是这样的:

  new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);

所以它不会在有空格的 URL 上中断(以格式错误的 URL 为借口)。但是,在对以下 url 进行编码时:

http://www.****.ca/en-ca/Catalog/Gallery.aspx?ID=Mass%20Spectrometry%20[GC/MS%20and%20ICP-MS]&PID=Gas%20Chromatography%20Mass%20Spectrometry%20Consumables

它将所有的 %20 转换为 %2520,导致地址无效。

Java 中有没有办法正确解析各种 URL?包括那些同时有 %20 和空格的?就像浏览器或 wget 命令一样。

【问题讨论】:

    标签: java http uri


    【解决方案1】:

    这是我自己的解决方案,目前有效,但我不知道它是否会在另一个奇怪的 URI 字符串上中断:

      public static URI uri(String s) throws URISyntaxException {
        try {
          return new URI(s);
        }
        catch (URISyntaxException e) {
          try {
            URL url = new URL(s);
            return new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
          } catch (MalformedURLException ee) {
            URL url;
            try {
              url = new URL(dummyURL, s);
            } catch (MalformedURLException eee) {
              throw new RuntimeException(eee);
            }
            return new URI(null, null, url.getPath(), url.getQuery(), null); //this will generate a relative URI the string itself is relative
          }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多