【发布时间】:2020-02-10 01:48:54
【问题描述】:
我需要解析可能包含与 http 或 https... 不同的协议的 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 包含不同于 http 或 https 的协议,我将其保存在一个变量中,然后强制 http 让 java.net.URL 解析它而不会崩溃。
有没有更优雅的方法来解决这个问题?
【问题讨论】:
-
您是否有理由不能使用
java.net.URI而不是java.net.URL? stackoverflow.com/questions/2406518/… -
是的……它有效。谢谢,我没有意识到;-)