j3d
j3d

Reputation: 9734

How to extract hostname and port from URL string?

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?

Upvotes: 6

Views: 7197

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108121

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

Upvotes: 19

Related Questions