【问题标题】:Scala: How to parse a URL with custom protocolsScala:如何使用自定义协议解析 URL
【发布时间】:2020-02-10 01:48:54
【问题描述】:

我需要解析可能包含与 httphttps... 不同的协议的 URL,因为如果尝试使用类似 nio://localhost:61616 的 URL 创建 java.net.URL 对象,构造函数会崩溃,我已经实现像这样:

def parseURL(spec: String): (String, String, Int, String) = {
  import java.net.URL

  var protocol: String = null

  val url = spec.split("://") match {
    case parts if parts.length > 1 =>
      protocol = parts(0)
      new URL(if (protocol == "http" || protocol == "https" ) spec else "http://" + parts(1))
    case _ => new URL("http" + spec.dropWhile(_ == '/'))
  } 

  var port = url.getPort; if (port < 0) port = url.getDefaultPort
  (protocol, url.getHost, port, url.getFile)
}

如果给定的 URL 包含不同于 httphttps 的协议,我将其保存在一个变量中,然后强制 httpjava.net.URL 解析它而不会崩溃。

有没有更优雅的方法来解决这个问题?

【问题讨论】:

标签: scala url parse-url


【解决方案1】:

您可以将 java.net.URI 用于任何非标准协议。

new java.net.URI("nio://localhost:61616").getScheme() // returns nio

如果您想要更类似于 Scala 的 API,可以查看 https://github.com/lemonlabsuk/scala-uri

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2019-12-20
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多