Parsing URLs
suggest changeKotlin 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:
- splitting a URL into scheme, host, port, path, query and fragment with
java.net.URI - handling invalid input
- raw (percent-encoded) and decoded components
- parsing a query string into a map
- building URLs and encoding values correctly
- resolving relative links, normalizing, relativizing
- validating user-supplied URLs
UrlandURLBuilderfrom Ktor
URI, not URL
The JDK has two classes, java.net.URL and java.net.URI. Use URI for parsing:
- The
URLconstructors are deprecated since Java 20. URL.equals()andURL.hashCode()resolve the host name through DNS. PuttingURLobjects in aHashSetcan block on network calls, and two URLs on different hosts that share an IP address compare as equal.URIonly parses and compares strings. It does no I/O.
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:
- Always pass a charset to
URLDecoder.decode()andURLEncoder.encode(). TheCharsetoverloads exist since Java 10 and don't throwUnsupportedEncodingException. Use UTF-8. - A parameter can appear more than once (
tag=sale&tag=new), so the result isMap<String, List<String>>. UsefirstOrNull()when you expect one value. empty=and a bareflagboth produce an empty string. If you need to tell them apart, useString?for the value.- The last line shows the bug you get from splitting the decoded
query:op=a%26bturns into two broken parameters. URLDecoderthrowsIllegalArgumentExceptionon a broken escape such as%G1or a trailing%. Catch it when the input comes from outside.
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
URLEncoder.encode()producesapplication/x-www-form-urlencodedtext: spaces become+, and&,=,/,?are escaped. That's correct for query names and values.- It's wrong for path segments.
my+report.pdfin a path means a file with a plus in its name. Use%20for spaces in paths:URLEncoder.encode(s, UTF_8).replace("+", "%20")is a common workaround. - The multi-argument
URIconstructors take decoded components and escape illegal characters in each one. They don't escape&or=inside the query argument, because they can't know whether those are separators. Use them for paths and fragments, and encode query values yourself. toString()keeps non-ASCII characters such aséas they are.toASCIIString()percent-encodes them as UTF-8, which is what you want to send over HTTP.
Resolving relative links
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
normalize()removes.and..segments.relativize()returns the input unchanged when it isn't under the base URI.?page=2resolves to.../guide/?page=2. RFC 3986 says the result should be.../guide/intro.html?page=2, which is what browsers do.java.net.URIimplements the older RFC 2396 and gets this case wrong. If you resolve links from HTML, handle query-only references yourself, or let jsoup do it withelement.absUrl("href")(see Parsing HTML).
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
example.com/pagehas no scheme, so the whole string is a relative path andhostisnull. If users type addresses withouthttps://, add the scheme before parsing.mailto:is an opaque URI. It has no host or path, only a scheme-specific part.- Check the scheme against an allow list. Links taken from user input and rendered as
hrefmust not allowjavascript:. my_host.example.comgiveshost = nullbecause an underscore isn't allowed in host names.URIfalls back to a "registry-based" authority and keeps the text inauthority. Code that only checkshosttreats such URLs as invalid. Some real host names contain underscores, so decide whether you need to accept them.
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
URIdoesn't accept non-ASCII host names:hostisnullforhttps://bücher.example/. Convert withIDN.toASCII()first.URI.equals()ignores case in the scheme, the host and the hex digits of%XXescapes. Paths, queries and fragments are compared case-sensitively.- It doesn't apply default ports or remove
..segments. Callnormalize()and drop explicit default ports yourself before comparing URIs or using them as map keys.
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
Url(String)is lenient. Input without a scheme is treated as a relative URL onhttp://localhost, and spaces are encoded, soUrl("not a url")succeeds. UseparseUrl()for untrusted input: it returnsnullwhen the string isn't an absolute URL.portreturns the default port of the protocol when none is given.specifiedPortreturns what's in the URL.segmentsandparametersare already split and decoded correctly, so the%2Fand%26problems shown earlier don't occur.URLBuilderencodes path segments with%20and query values with+, which is the correct encoding for each part.Urlobjects are immutable. Copy one intoURLBuilder(url)to change it.- The Ktor client uses the same types (
client.get { url { ... } }), see HTTP client. On the server,call.request.queryParametersgives the parsed query string.
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 {} |