【问题标题】:Java How to Normalise a URL and Remove FragmentJava 如何规范化 URL 和删除片段
【发布时间】:2017-04-26 17:07:17
【问题描述】:

如何在 Java 中规范化 URL 以删除片段。 IE。从https://www.website.com#somethinghttps://www.website.com

这可以通过 URL.Normalize 代码实现,尽管在这个特定的用例中,我只有一个完整的绝对 URL,需要保持完整。

我希望能够稍微修改此代码以从 URL 中删除片段;

//The website below is just an example. In reality, this URL is unknown and could be anything. Both with and without a fragment depending on the use case
URL absUrl = new URL("https://www.website.com#something");

到目前为止,我的想法是,这只有通过将 URL 分解为协议 + 域 + 路径然后将它们重新组合在一起才能实现,这似乎确实有效,但必须有一种更优雅的方法这。

【问题讨论】:

  • 您还可以使用substringindexOf 使用# 字符。
  • # 可能并不总是存在,因此首先需要进行更多检查。但有可能。

标签: java


【解决方案1】:

片段在 Java URL 中不作为单独的实体存在。但是您可以将 URL 转换为 URI 并返回以删除片段。我是这样做的:

URL url;
...
if (url.toString().contains("#")) {
  URI uri = null;
  try {
    uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), null);
    String file = "";
    if (uri.getPath() != null) {
      file += uri.getPath();
    }
    if (uri.getQuery() != null) {
      file += uri.getQuery();                                       
    }
    url = new URL(uri.getScheme(), uri.getHost(), uri.getPort(), file);
  } catch (URISyntaxException e) {
    ...
  } catch (MalformedURLException e) {
    ...             
  }
}

【讨论】:

    【解决方案2】:

    使用转换方法toURItoURL 删除片段相当简单。因此要将 URL 转换为 URI:

    URL url = /*what have you*/ …
    URI u = url.toURI();
    

    要从 URI 中删除任何片段:

    if( u.getFragment() != null ) { // Remake with same parts, less the fragment:
        u = new URI( u.getScheme(), u.getSchemeSpecificPart(), /*fragment*/null ); }
    

    在像这样从其部分重构URI 时,使用解码的getter(如图所示)很重要,而不是相应的原始getter。有关此用法的权限,请参见例如API身份部分。

    要将结果转换回 URL:

    url = u.toURL();
    

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 2012-05-22
      • 2011-03-22
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 2011-08-04
      相关资源
      最近更新 更多