Parsing URLs

suggest change

Kotlin on the JVM has no URL type of its own. You use java.net.URI from the JDK, or a library type such as Ktor's Url when you already depend on Ktor.

This article covers:

URI, not URL

The JDK has two classes, java.net.URL and java.net.URI. Use URI for parsing:

When an API needs a URL, convert at the last moment with uri.toURL().

Parts of a URL

import java.net.URI

fun main() {
    val uri = URI("https://ann:secret@shop.example.com:8443/products/search?q=red+shoes&size=42#reviews")

    println("scheme:    ${uri.scheme}")
    println("userInfo:  ${uri.userInfo}")
    println("host:      ${uri.host}")
    println("port:      ${uri.port}")
    println("authority: ${uri.authority}")
    println("path:      ${uri.path}")
    println("query:     ${uri.query}")
    println("fragment:  ${uri.fragment}")

    val noPort = URI("https://example.com/")
    println("port when missing: ${noPort.port}")
    println("effective port: ${noPort.port.takeIf { it != -1 } ?: defaultPort(noPort.scheme)}")
}

fun defaultPort(scheme: String?): Int = when (scheme?.lowercase()) {
    "http", "ws" -> 80
    "https", "wss" -> 443
    "ftp" -> 21
    else -> -1
}

Output:

scheme:    https
userInfo:  ann:secret
host:      shop.example.com
port:      8443
authority: ann:secret@shop.example.com:8443
path:      /products/search
query:     q=red+shoes&size=42
fragment:  reviews
port when missing: -1
effective port: 443

Missing parts are null, and a missing port is -1. URI doesn't know default ports, so you have to supply them yourself as defaultPort() does.

The getters are Java methods (getHost(), getPort()), so Kotlin lets you call them as properties.

Invalid input

The URI constructor throws the checked URISyntaxException. URI.create() throws an unchecked IllegalArgumentException and is meant for constant strings in your own code:

import java.net.URI
import java.net.URISyntaxException

fun parseUriOrNull(s: String): URI? =
    try { URI(s) } catch (e: URISyntaxException) { null }

fun main() {
    try {
        URI("https://example.com/my file.txt")
    } catch (e: URISyntaxException) {
        println("URISyntaxException: ${e.message}")
        println("reason=${e.reason} index=${e.index}")
    }

    try {
        URI.create("https://example.com/a|b")
    } catch (e: IllegalArgumentException) {
        println("IllegalArgumentException: ${e.message}")
    }

    println(parseUriOrNull("https://example.com/ok"))
    println(parseUriOrNull("http://[::1"))
}

Output:

URISyntaxException: Illegal character in path at index 22: https://example.com/my file.txt
reason=Illegal character in path index=22
IllegalArgumentException: Illegal character in path at index 21: https://example.com/a|b
https://example.com/ok
null

URI follows RFC 2396 strictly. Spaces, |, {, }, " and ^ are rejected. Browsers accept them and fix them silently, so URLs copied from an address bar, pasted by users or scraped from HTML can fail to parse. Don't try to fix such strings with search and replace. Use the multi-argument constructors or a builder (shown below), which encode each component on its own.

Kotlin's runCatching { URI(s) }.getOrNull() also works, but it catches every exception, not just URISyntaxException.

Raw and decoded components

Every component has two getters. path, query and fragment return decoded text. rawPath, rawQuery and rawFragment return the text as it appears in the URL, with %XX escapes intact:

import java.net.URI

fun main() {
    val uri = URI("https://example.com/docs/caf%C3%A9%20menu/a%2Fb?name=J%C3%BCrgen&x=1%262#sec%201")

    println("path:        ${uri.path}")
    println("rawPath:     ${uri.rawPath}")
    println("query:       ${uri.query}")
    println("rawQuery:    ${uri.rawQuery}")
    println("fragment:    ${uri.fragment}")
    println("rawFragment: ${uri.rawFragment}")
}

Output:

path:        /docs/café menu/a/b
rawPath:     /docs/caf%C3%A9%20menu/a%2Fb
query:       name=Jürgen&x=1&2
rawQuery:    name=J%C3%BCrgen&x=1%262
fragment:    sec 1
rawFragment: sec%201

Decoding loses information. The path segment a%2Fb is one segment containing a slash, but the decoded path shows a/b, which looks like two segments. The query value 1%262 is 1&2, but the decoded query x=1&2 looks like two parameters.

The rule: split on / or & first using the raw getter, then decode each piece:

import java.net.URI
fun main() {
    val uri = URI("https://example.com/docs/caf%C3%A9%20menu/a%2Fb/1+1")
    val segments = uri.rawPath.split('/').filter { it.isNotEmpty() }
        .map { java.net.URLDecoder.decode(it.replace("+", "%2B"), Charsets.UTF_8) }
    println(segments)
}

Output:

[docs, café menu, a/b, 1+1]

URLDecoder implements form decoding, where + means a space. In a path + is a literal plus sign, which is why it's escaped as %2B before decoding.

Parsing a query string

The JDK has no query string parser. Write a small function that splits the raw query, decodes each name and value, and groups repeated names:

import java.net.URI
import java.net.URLDecoder

fun parseQuery(rawQuery: String?): Map<String, List<String>> {
    if (rawQuery.isNullOrEmpty()) return emptyMap()
    return rawQuery.split('&')
        .filter { it.isNotEmpty() }
        .map { pair ->
            val name = pair.substringBefore('=')
            val value = if ('=' in pair) pair.substringAfter('=') else ""
            URLDecoder.decode(name, Charsets.UTF_8) to URLDecoder.decode(value, Charsets.UTF_8)
        }
        .groupBy({ it.first }, { it.second })
}

fun main() {
    val uri = URI("https://example.com/search?q=red+shoes&tag=sale&tag=new&city=Z%C3%BCrich&empty=&flag&op=a%26b")
    val params = parseQuery(uri.rawQuery)

    for ((name, values) in params) println("$name -> ${values.map { "\"$it\"" }}")

    println("q = ${params["q"]?.firstOrNull()}")
    println("page = ${params["page"]?.firstOrNull()?.toIntOrNull() ?: 1}")

    // the wrong way: decoded query loses the difference between & and %26
    println(uri.query.split('&'))
}

Output:

q -> ["red shoes"]
tag -> ["sale", "new"]
city -> ["Zürich"]
empty -> [""]
flag -> [""]
op -> ["a&b"]
q = red shoes
page = 1
[q=red+shoes, tag=sale, tag=new, city=Zürich, empty=, flag, op=a, b]

Details worth knowing:

Values from a query string are always strings. Convert with toIntOrNull(), toBooleanStrictOrNull() and friends, and provide defaults with ?:. See Type conversion.

Building URLs

Never build URLs by concatenating unencoded user input. Encode each query parameter name and value:

import java.net.URI
import java.net.URLEncoder

fun buildQuery(params: Map<String, Any?>): String =
    params.entries
        .filter { it.value != null }
        .joinToString("&") { (k, v) ->
            URLEncoder.encode(k, Charsets.UTF_8) + "=" + URLEncoder.encode(v.toString(), Charsets.UTF_8)
        }

fun main() {
    val query = buildQuery(mapOf("q" to "red shoes & socks", "city" to "Zürich", "page" to 2, "debug" to null))
    val uri = URI.create("https://example.com/search?$query")
    println(uri)
    println(uri.toURL())

    // URLEncoder is for form data: wrong for path segments
    println("/files/" + URLEncoder.encode("my report.pdf", Charsets.UTF_8))

    // the multi-argument constructors quote illegal characters per component
    val u2 = URI("https", "example.com", "/files/my report.pdf", "note=a b", "top")
    println(u2)
    println(u2.toASCIIString())
    val u3 = URI("https", null, "example.com", 8080, "/café/menu", null, null)
    println(u3.toASCIIString())
}

Output:

https://example.com/search?q=red+shoes+%26+socks&city=Z%C3%BCrich&page=2
https://example.com/search?q=red+shoes+%26+socks&city=Z%C3%BCrich&page=2
/files/my+report.pdf
https://example.com/files/my%20report.pdf?note=a%20b#top
https://example.com/files/my%20report.pdf?note=a%20b#top
https://example.com:8080/caf%C3%A9/menu

resolve() turns a relative reference into an absolute URL, the way a browser handles href attributes. This is the core of a web crawler (see Web scraping):

import java.net.URI

fun main() {
    val base = URI("https://example.com/docs/guide/intro.html")

    for (ref in listOf("setup.html", "../api/index.html", "/about", "?page=2", "#install", "//cdn.example.net/app.js", "https://other.org/x")) {
        println("%-26s -> %s".format(ref, base.resolve(ref)))
    }

    println(URI("https://example.com/a/./b/../c//d").normalize())

    val root = URI("https://example.com/docs/")
    println(root.relativize(URI("https://example.com/docs/guide/intro.html")))
    println(root.relativize(URI("https://example.com/blog/post")))
}

Output:

setup.html                 -> https://example.com/docs/guide/setup.html
../api/index.html          -> https://example.com/docs/api/index.html
/about                     -> https://example.com/about
?page=2                    -> https://example.com/docs/guide/?page=2
#install                   -> https://example.com/docs/guide/intro.html#install
//cdn.example.net/app.js   -> https://cdn.example.net/app.js
https://other.org/x        -> https://other.org/x
https://example.com/a/c/d
guide/intro.html
https://example.com/blog/post

Validating user input

A string that parses as a URI isn't necessarily a web address. A relative path, a mailto: link or a javascript: URI all parse fine:

import java.net.URI
import java.net.URISyntaxException

fun isHttpUrl(s: String): Boolean {
    val uri = try { URI(s) } catch (e: URISyntaxException) { return false }
    return uri.scheme?.lowercase() in setOf("http", "https") && !uri.host.isNullOrEmpty()
}

fun main() {
    for (s in listOf("example.com/page", "mailto:ann@example.com", "file:///C:/temp/a.txt", "https://my_host.example.com/")) {
        val u = URI(s)
        println("$s: scheme=${u.scheme} host=${u.host} authority=${u.authority} path=${u.path} opaque=${u.isOpaque} absolute=${u.isAbsolute}")
    }
    println("mailto ssp: " + URI("mailto:ann@example.com").schemeSpecificPart)
    println()
    for (s in listOf("https://example.com", "HTTP://Example.com/x", "ftp://example.com", "example.com", "https:///path", "javascript:alert(1)", "https://exa mple.com")) {
        println("%-24s %s".format(s, isHttpUrl(s)))
    }
}

Output:

example.com/page: scheme=null host=null authority=null path=example.com/page opaque=false absolute=false
mailto:ann@example.com: scheme=mailto host=null authority=null path=null opaque=true absolute=true
file:///C:/temp/a.txt: scheme=file host=null authority=null path=/C:/temp/a.txt opaque=false absolute=true
https://my_host.example.com/: scheme=https host=null authority=my_host.example.com path=/ opaque=false absolute=true
mailto ssp: ann@example.com

https://example.com      true
HTTP://Example.com/x     true
ftp://example.com        false
example.com              false
https:///path            false
javascript:alert(1)      false
https://exa mple.com     false

Validating a URL doesn't make it safe to fetch. When a server downloads URLs supplied by users (webhooks, link previews), also check the IP address the host resolves to, and refuse loopback, private and link-local ranges to prevent server-side request forgery.

International domain names and comparison

Non-ASCII host names must be converted to their ASCII ("punycode") form, both for parsing and for DNS:

import java.net.IDN
import java.net.URI

fun main() {
    val host = "bücher.example"
    val ascii = IDN.toASCII(host)
    println(ascii)
    println(IDN.toUnicode(ascii))
    println(URI("https://$ascii/").host)
    println(URI("https://$host/").host)
    println(URI("HTTPS://Example.COM/Path") == URI("https://example.com/Path"))
    println(URI("https://example.com/a%2fb") == URI("https://example.com/a%2Fb"))
}

Output:

xn--bcher-kva.example
bücher.example
xn--bcher-kva.example
null
true
true

Ktor Url and URLBuilder

If your project uses Ktor (client or server), the ktor-http module has a Kotlin URL type with a parsed query string and a builder:

dependencies {
    implementation("io.ktor:ktor-http:3.6.0")
}
import io.ktor.http.*

fun main() {
    val url = Url("https://shop.example.com:8443/products/search?q=red+shoes&tag=sale&tag=new#reviews")

    println(url.protocol.name)
    println(url.host)
    println(url.port)
    println(url.specifiedPort)
    println(url.segments)
    println(url.encodedPath)
    println(url.parameters["q"])
    println(url.parameters.getAll("tag"))
    println(url.fragment)

    println(Url("not a url"))
    println(parseUrl("not a url"))
    println(parseUrl("https://example.com/ok")?.host)

    val built = buildUrl {
        protocol = URLProtocol.HTTPS
        host = "api.example.com"
        appendPathSegments("v1", "files", "my report.pdf")
        parameters.append("q", "red shoes & socks")
        parameters.append("city", "Zürich")
    }
    println(built)

    val next = URLBuilder(url).apply {
        parameters.remove("tag")
        parameters["page"] = "2"
        fragment = ""
    }.build()
    println(next)
}

Output:

https
shop.example.com
8443
8443
[products, search]
/products/search
red shoes
[sale, new]
reviews
http://localhost/not%20a%20url
null
example.com
https://api.example.com/v1/files/my%20report.pdf?q=red+shoes+%26+socks&city=Z%C3%BCrich
https://shop.example.com:8443/products/search?q=red+shoes&page=2

Other options are OkHttp's HttpUrl ("https://...".toHttpUrlOrNull()), which follows the WHATWG URL standard used by browsers, and Spring's UriComponentsBuilder in Spring applications.

Summary

Task Use
Parse a URL URI(s) (checked exception) or URI.create(s) for constants
Get decoded parts path, query, fragment
Split a path or query rawPath, rawQuery, then decode each piece
Decode and encode query values URLDecoder.decode(s, UTF_8), URLEncoder.encode(s, UTF_8)
Make a link absolute base.resolve(href)
Remove . and .. normalize()
Non-ASCII host IDN.toASCII(host)
Send over the network toASCIIString(), toURL()
Kotlin-friendly parsing and building Ktor Url, parseUrl(), URLBuilder, buildUrl {}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents