7

I need to extract hostname and port (if any) from an URL and here below is my code:

val regEx = """^(?:https?:\/\/)?(?:www\.)?(.*?)\//""".r
val url = regEx.split("http://www.domain.com:8080/one/two")
val hostname = url(url.length - 1).split("/")(0).split(":")(0)
val hasPort = url(url.length - 1).split("/")(0).split(":").length > 1
val port = if (hasPort) url(url.length - 1).split("/")(0).split(":")(1) else 80

The code above works as expected... but for sure in Scala there is a better way to get the same result.

How do I get hostname and port (if any) without using all those ugly splits?

1
  • Yes... that was the idea... but in this case I think what suggests Gabriele is the best solution. Tx. Commented Jan 25, 2015 at 15:08

1 Answer 1

19

Without reinventing the wheel, you can simply leverage java.net.URL

val url = new java.net.URL("http://www.domain.com:8080/one/two")
val hostname = url.getHost // www.domain.com
val port = url.getPort     // 8080

A minor difference, getPort returns -1 if no port is specified, so you have to handle that case explicitly.

val port = if (url.getPort == -1) url.getDefaultPort else url.getPort
Sign up to request clarification or add additional context in comments.

1 Comment

Note you should use new java.net.URI if you have urls like ws://domain.com:1234 (websockets). java.net.URL will throw on the ws protocol but java.net.URI is fine with it. java.net.URI has getHost and getPort too.

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.