3

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?

2
  • 2
    Do you have a reason that you cannot use java.net.URI instead of java.net.URL ? stackoverflow.com/questions/2406518/… Commented Sep 25, 2015 at 1:08
  • Yes... it works. Thanks, I didn't realize ;-) Commented Sep 25, 2015 at 6:05

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.