我需要解析可能包含与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解析它而不会崩溃。
有没有更优雅的方法来解决这个问题?