Scala:如何使用自定义协议解析 URL

Scala: How to parse a URL with custom protocols

我需要解析可能包含不同于 httphttps 的协议的 URLs... 因为如果尝试创建一个 java.net.URL 对象URL 就像 nio://localhost:61616 构造函数崩溃,我已经实现了这样的东西:

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 解析它而不会崩溃。

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

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

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

如果你想要更像 API 的 Scala,你可以查看 https://github.com/lemonlabsuk/scala-uri