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

j3d*_*j3d 3 url scala parse-url

我需要解析可能包含不同于http或者https...的协议的URL,因为如果尝试创建一个java.net.URLnio://localhost:61616构造函数崩溃这样的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)
}
Run Code Online (Sandbox Code Playgroud)

如果一个给定的URL包含比不同的协议http或者https,我把它保存在一个变量,然后我强迫httpjava.net.URL解析它不会崩溃.

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

sur*_*nto 10

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

new java.net.URI("nio://localhost:61616").getScheme() // returns nio
Run Code Online (Sandbox Code Playgroud)

如果您想要更多类似Scala的Scala,可以查看https://github.com/NET-A-PORTER/scala-uri.