【问题标题】:Convert partial url string to full url string将部分 url 字符串转换为完整 url 字符串
【发布时间】:2015-09-04 16:54:21
【问题描述】:

我正在开发一个网络浏览器。是否有内置方法可以将部分 url 字符串(如 "example.com""www.example.com" 等)转换为 "http://www.example.com/"

【问题讨论】:

  • gmail.com 既不是 URL 也不是 URI。它是一个域。
  • 维基百科总是很好。 en.wikipedia.org/wiki/…
  • 我想你没有意识到我的问题。我编辑了我的帖子。
  • 请注意,www. 不一定是有效的子域(例如,en.wikipedia.org 有效,但 www.en.wikipedia.org 无效)。

标签: java string url uri


【解决方案1】:

我不确定这是否会解决您的问题 - 但我可能会建议使用内置 URL 类来尝试解决此问题。请查看下面的链接并确定它们是否有用。

https://docs.oracle.com/javase/tutorial/networking/urls/

Building an absolute URL from a relative URL in Java

http://docs.oracle.com/javase/7/docs/api/java/net/URL.html

【讨论】:

    【解决方案2】:

    假设您正在尝试对在 Web 浏览器的地址栏中键入的 String 进行操作,那么您唯一可以放心地做的就是检查该字符串是否已经以“http://”或“https”开头://”或其他一些方案(例如“ftp://”),如果不是,则在开头添加“http://”。

    正如在 cmets 中提到的,假设子域应该设置为“www”是错误的,因为并非所有 Web 服务器都配置了这个子域。 (如果网站所有者愿意,很容易将 Web 服务器配置为将请求重定向到“www”子域。)

    所以我想说你需要的代码就是这样的:

    // Create a static final class field.
    static final Pattern STARTS_WITH_SCHEME = Pattern.compile("^ *[a-z]+://");
    
    // Then within your method code make use of the Pattern.
    if (!STARTS_WITH_SCHEME.matcher(urlString).find()) {
        urlString = "http://" + urlString.trim();
    }
    

    这将检查您的urlString 是否以任何方案开头,后跟冒号和双斜杠。如果没有,那么“http://”将被添加到您的urlString。请注意,Pattern 允许空格出现在urlString 的开头,然后方法代码会将它们修剪掉。

    【讨论】:

      【解决方案3】:

      从我从你的问题中了解到,这是你假装的。

      String url = "www.example.com"
      
      //Checks if the string does not start with http://
      if (!url.startsWith("http://" && !url.endsWith("/") {
          //Appends the http in the begginning of the String
          url.insert(0, "http://");
      }
      //Checks if the string does not end with /
      if (!url.endsWith("/") {
          //Appends the slash in the end of the url
          url.append("/");
      }
      

      注意我添加了url String的验证,因为在某些情况下我猜你不确定url格式。

      【讨论】:

      • 这并不能处理所有情况...我确信有一种内置方法可以将所有情况转换为正确的 url
      • 不能忘记末尾的“/” - !url.endsWIth("/")
      • @Sh4d0wsPlyr 谢谢,我没有注意到那部分。更新了我的答案。
      • 您可能希望对!url.endsWith("/") 进行单独检查,因为字符串可以有一个但不能有另一个。
      • @SaharAvr 据我所知,没有内置的,所以你只需要手动完成。这只是处理字符串的问题。
      猜你喜欢
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多