Skip to content



[jvm]\ class HttpUrl

A uniform resource locator (URL) with a scheme of either http or https. Use this class to compose and decompose Internet addresses. For example, this code will compose and print a URL for Google search:

HttpUrl url = new HttpUrl.Builder()\ .scheme("https")\ .host("")\ .addPathSegment("search")\ .addQueryParameter("q", "polar bears")\ .build();\ System.out.println(url);

which prints:

As another example, this code prints the human-readable query parameters of a Twitter search:

HttpUrl url = HttpUrl.parse(";);\ for (int i = 0, size = url.querySize(); i < size; i++) {\ System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i));\ }

which prints:

q: cute #puppies\ f: images

In addition to composing URLs from their component parts and decomposing URLs into their component parts, this class implements relative URL resolution: what address you’d reach by clicking a relative link on a specified page. For example:

HttpUrl base = HttpUrl.parse(";);\ HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc");\ System.out.println(link);

which prints:

What’s in a URL?

A URL has several components.


Sometimes referred to as protocol, A URL’s scheme describes what mechanism should be used to retrieve the resource. Although URLs have many schemes (mailto, file, ftp), this class only supports http and https. Use for URLs with arbitrary schemes.

Username and Password

Username and password are either present, or the empty string "" if absent. This class offers no mechanism to differentiate empty from absent. Neither of these components are popular in practice. Typically HTTP applications use other mechanisms for user identification and authentication.


The host identifies the webserver that serves the URL’s resource. It is either a hostname like or localhost, an IPv4 address like, or an IPv6 address like ::1.

Usually a webserver is reachable with multiple identifiers: its IP addresses, registered domain names, and even localhost when connecting from the server itself. Each of a web server’s names is a distinct URL and they are not interchangeable. For example, even if and are served by the same IP address, the two URLs identify different resources.


The port used to connect to the web server. By default this is 80 for HTTP and 443 for HTTPS. This class never returns -1 for the port: if no port is explicitly specified in the URL then the scheme’s default is used.


The path identifies a specific resource on the host. Paths have a hierarchical structure like "/square/okhttp/issues/1486" and decompose into a list of segments like ["square", "okhttp", "issues", "1486"].

This class offers methods to compose and decompose paths by segment. It composes each path from a list of segments by alternating between "/" and the encoded segment. For example the segments ["a", "b"] build "/a/b" and the segments ["a", "b", ""] build "/a/b/".

If a path’s last segment is the empty string then the path ends with "/". This class always builds non-empty paths: if the path is omitted it defaults to "/". The default path’s segment list is a single empty string: [""].


The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query string is subdivided into a collection of name-value parameters. This class offers methods to set the query as the single string, or as individual name-value parameters. With name-value parameters the values are optional and names may be repeated.


The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and query the fragment is not sent to the webserver: it’s private to the client.


Each component must be encoded before it is embedded in the complete URL. As we saw above, the string cute #puppies is encoded as cute%20%23puppies when used as a query parameter value.

Percent encoding

Percent encoding replaces a character (like \ud83c\udf69) with its UTF-8 hex bytes (like %F0%9F%8D%A9). This approach works for whitespace characters, control characters, non-ASCII characters, and characters that already have another meaning in a particular context.

Percent encoding is used in every URL component except for the hostname. But the set of characters that need to be encoded is different for each component. For example, the path component must escape all of its ? characters, otherwise it could be interpreted as the start of the URL’s query. But within the query and fragment components, the ? character doesn’t delimit anything and doesn’t need to be escaped.

HttpUrl url = HttpUrl.parse("http://who-let-the-dogs.out").newBuilder()\ .addPathSegment("Who?")\ .query("Who?")\ .fragment("Who?")\ .build();\ System.out.println(url);

This prints:


When parsing URLs that lack percent encoding where it is required, this class will percent encode the offending characters.

IDNA Mapping and Punycode encoding

Hostnames have different requirements and use a different encoding scheme. It consists of IDNA mapping and Punycode encoding.

In order to avoid confusion and discourage phishing attacks, IDNA Mapping transforms names to avoid confusing characters. This includes basic case folding: transforming shouting SQUARE.COM into cool and casual It also handles more exotic characters. For example, the Unicode trademark sign (™) could be confused for the letters "TM" in http://ho™ To mitigate this, the single character (™) maps to the string ™. There is similar policy for all of the 1.1 million Unicode code points. Note that some code points such as "\ud83c\udf69" are not mapped and cannot be used in a hostname.

Punycode converts a Unicode string to an ASCII string to make international domain names work everywhere. For example, "σ" encodes as "xn–4xa". The encoded string is not human readable, but can be used with classes like InetAddress to establish connections.

Why another URL model?

Java includes both and We offer a new URL model to address problems that the others don’t.

Different URLs should be different

Although they have different content, considers the following two URLs equal, and the equals() method between them returns true:

This is because those two hosts share the same IP address. This is an old, bad design decision that makes unusable for many things. It shouldn’t be used as a Map key or in a Set. Doing so is both inefficient because equality may require a DNS lookup, and incorrect because unequal URLs may be equal because of how they are hosted.

Equal URLs should be equal

These two URLs are semantically identical, but disagrees:

Both the unnecessary port specification (:80) and the absent trailing slash (/) cause URI to bucket the two URLs separately. This harms URI’s usefulness in collections. Any application that stores information-per-URL will need to either canonicalize manually, or suffer unnecessary redundancy for such URLs.

Because they don’t attempt canonical form, these classes are surprisingly difficult to use securely. Suppose you’re building a webservice that checks that incoming paths are prefixed "/static/images/" before serving the corresponding assets from the filesystem.

String attack = ";;\ System.out.println(new URL(attack).getPath());\ System.out.println(new URI(attack).getPath());\ System.out.println(HttpUrl.parse(attack).encodedPath());

By canonicalizing the input paths, they are complicit in directory traversal attacks. Code that checks only the path prefix may suffer!

/static/images/../../../../../etc/passwd\ /static/images/../../../../../etc/passwd\ /etc/passwd

If it works on the web, it should work in your application

The class is strict around what URLs it accepts. It rejects URLs like|def because the | character is unsupported. This class is more forgiving: it will automatically percent-encode the |’ yielding This kind behavior is consistent with web browsers. HttpUrl prefers consistency with major web browsers over consistency with obsolete specifications.

Paths and Queries should decompose

Neither of the built-in URL models offer direct access to path segments or query parameters. Manually using StringBuilder to assemble these components is cumbersome: do ‘+’ characters get silently replaced with spaces? If a query parameter contains a ‘&’, does that get escaped? By offering methods to read and write individual query parameters directly, application developers are saved from the hassles of encoding and decoding.

Plus a modern API

The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping constructors. For example, there’s no API to compose a URI with a custom port without also providing a query and fragment.

Instances of HttpUrl are well-formed and always have a scheme, host, and path. With it’s possible to create an awkward URL like http:/ with scheme and path but no hostname. Building APIs that consume such malformed values is difficult!

This class has a modern API. It avoids punitive checked exceptions: toHttpUrl throws IllegalArgumentException on invalid input or toHttpUrlOrNull returns null if the input is an invalid URL. You can even be explicit about whether each component has been encoded already.


Name Summary
Builder [jvm]
class Builder
Companion [jvm]
object Companion


Name Summary
equals [jvm]
open operator override fun equals(other: Any?): Boolean
hashCode [jvm]
open override fun hashCode(): Int
newBuilder [jvm]
fun newBuilder(): HttpUrl.Builder
Returns a builder based on this URL.
fun newBuilder(link: String): HttpUrl.Builder?
Returns a builder for the URL that would be retrieved by following link from this URL, or null if the resulting URL is not well-formed.
queryParameter [jvm]
fun queryParameter(name: String): String?
The first query parameter named name decoded using UTF-8, or null if there is no such query parameter.
queryParameterName [jvm]
fun queryParameterName(index: Int): String
Returns the name of the query parameter at index. For example this returns "a" for queryParameterName(0) on http://host/?a=apple&b=banana. This throws if index is not less than the query size.
queryParameterValue [jvm]
fun queryParameterValue(index: Int): String?
Returns the value of the query parameter at index. For example this returns "apple" for queryParameterName(0) on http://host/?a=apple&b=banana. This throws if index is not less than the query size.
queryParameterValues [jvm]
fun queryParameterValues(name: String): List<String?>
Returns all values for the query parameter name ordered by their appearance in this URL. For example this returns ["banana"] for queryParameterValue("b") on http://host/?a=apple&b=banana.
redact [jvm]
fun redact(): String
Returns a string with containing this URL with its username, password, query, and fragment stripped, and its path replaced with /.... For example, redacting returns
resolve [jvm]
fun resolve(link: String): HttpUrl?
Returns the URL that would be retrieved by following link from this URL, or null if the resulting URL is not well-formed.
topPrivateDomain [jvm]
fun topPrivateDomain(): String?
Returns the domain name of this URL’s host that is one level beneath the public suffix by consulting the public suffix list. Returns null if this URL’s host is an IP address or is considered a public suffix by the public suffix list.
toString [jvm]
open override fun toString(): String
toUri [jvm]
@JvmName(name = "uri")
fun toUri(): URI
Returns this URL as a Because URI is more strict than this class, the returned URI may be semantically different from this URL:
toUrl [jvm]
@JvmName(name = "url")
fun toUrl(): URL
Returns this URL as a


Name Summary
encodedFragment [jvm]
@get:JvmName(name = "encodedFragment")
val encodedFragment: String?
This URL’s encoded fragment, like "abc" for http://host/#abc. This is null if the URL has no fragment.
encodedPassword [jvm]
@get:JvmName(name = "encodedPassword")
val encodedPassword: String
The password, or an empty string if none is set.
encodedPath [jvm]
@get:JvmName(name = "encodedPath")
val encodedPath: String
The entire path of this URL encoded for use in HTTP resource resolution. The returned path will start with "/".
encodedPathSegments [jvm]
@get:JvmName(name = "encodedPathSegments")
val encodedPathSegments: List<String>
A list of encoded path segments like ["a", "b", "c"] for the URL http://host/a/b/c. This list is never empty though it may contain a single empty string.
encodedQuery [jvm]
@get:JvmName(name = "encodedQuery")
val encodedQuery: String?
The query of this URL, encoded for use in HTTP resource resolution. This string may be null (for URLs with no query), empty (for URLs with an empty query) or non-empty (all other URLs).
encodedUsername [jvm]
@get:JvmName(name = "encodedUsername")
val encodedUsername: String
The username, or an empty string if none is set.
fragment [jvm]
@get:JvmName(name = "fragment")
val fragment: String?
This URL’s fragment, like "abc" for http://host/#abc. This is null if the URL has no fragment.
host [jvm]
@get:JvmName(name = "host")
val host: String
The host address suitable for use with InetAddress.getAllByName. May be:
isHttps [jvm]
val isHttps: Boolean
password [jvm]
@get:JvmName(name = "password")
val password: String
Returns the decoded password, or an empty string if none is present.
pathSegments [jvm]
@get:JvmName(name = "pathSegments")
val pathSegments: List<String>
A list of path segments like ["a", "b", "c"] for the URL http://host/a/b/c. This list is never empty though it may contain a single empty string.
pathSize [jvm]
@get:JvmName(name = "pathSize")
val pathSize: Int
The number of segments in this URL’s path. This is also the number of slashes in this URL’s path, like 3 in http://host/a/b/c. This is always at least 1.
port [jvm]
@get:JvmName(name = "port")
val port: Int
The explicitly-specified port if one was provided, or the default port for this URL’s scheme. For example, this returns 8443 for and 443 for The result is in [1..65535].
query [jvm]
@get:JvmName(name = "query")
val query: String?
This URL’s query, like "abc" for http://host/?abc. Most callers should prefer queryParameterName and queryParameterValue because these methods offer direct access to individual query parameters.
queryParameterNames [jvm]
@get:JvmName(name = "queryParameterNames")
val queryParameterNames: Set<String>
The distinct query parameter names in this URL, like ["a", "b"] for http://host/?a=apple&b=banana. If this URL has no query this is the empty set.
querySize [jvm]
@get:JvmName(name = "querySize")
val querySize: Int
The number of query parameters in this URL, like 2 for http://host/?a=apple&b=banana. If this URL has no query this is 0. Otherwise it is one more than the number of "&" separators in the query.
scheme [jvm]
@get:JvmName(name = "scheme")
val scheme: String
Either "http" or "https".
username [jvm]
@get:JvmName(name = "username")
val username: String
The decoded username, or an empty string if none is present.