I need to parse URLs that might contain protocols different than http
or https
... and since if try to create a java.net.URL
object with a URL like nio://localhost:61616
the constructor crashes, I've implemented something like this:
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)
}
In case a given URL contains a protocol different than http
or https
, I save it in a variable and then I force http
to let java.net.URL
parse it without crashing.
Is there a more elegant way to solve this problem?
You can use java.net.URI for any non standard protocol.
new java.net.URI("nio://localhost:61616").getScheme() // returns nio
If you want a more Scala like API, you can check out https://github.com/lemonlabsuk/scala-uri.