3

我需要解析可能包含与httpor不同的协议的 URL,https因为如果尝试使用构造函数崩溃之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 包含不同于httpor的协议https,我将它保存在一个变量中,然后我强制http让它java.net.URL解析它而不会崩溃。

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

4

1 回答 1

10

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

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

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

于 2015-09-25T06:42:46.650 回答