Java Reference ยท I/O and Files
The URI and URL classes
Reference for java.net.URI and URL: parse addresses, read their parts, resolve relative links, encode query values, and why URI is preferred over URL.
A URI is a string that identifies something, such as https://example.com/a/b?x=1#top. java.net.URI parses and builds these strings, splits them into scheme, host, port, path, query and fragment, and resolves relative references. It does not connect anywhere.
java.net.URL is the older class that can also open a connection. Its equals() and hashCode() can trigger DNS lookups, and the constructors are deprecated since Java 20. Prefer URI, and convert with URI.create(...).toURL() only when an API demands a URL.
URI uri = URI.create("https://example.com:8443/docs/intro?lang=en#top"); String host = uri.getHost(); // example.com
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public final class URI implements Comparable<URI>, Serializable static URI create(String str) URI(String str) throws URISyntaxException URI(String scheme, String host, String path, String fragment) throws URISyntaxException URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment)
| Member | Description |
|---|---|
getScheme(), getHost(), getPort(), getPath(), getQuery(), getFragment(), getUserInfo() |
The decoded parts; null when missing (-1 for a missing port). |
getRawPath(), getRawQuery() |
The parts exactly as written, still percent-encoded. |
URI resolve(String or URI) |
Resolves a (possibly relative) reference against this URI. |
URI relativize(URI) |
The reverse: a relative URI that leads from this one to another. |
URI normalize() |
Removes . and .. segments. |
URL toURL() |
Converts to a URL; throws IllegalArgumentException if not absolute. |
String toASCIIString() |
The string with non-ASCII characters percent-encoded. |
boolean isAbsolute() / isOpaque() |
Has a scheme / is something like mailto: with no / after the scheme. |
Throws: URISyntaxException (checked) from the constructors, IllegalArgumentException from create for the same problem.
Usage notes
URI.createis for literals. It wraps the checked exception, which is convenient when you know the string is valid and wrong for user input; catchIllegalArgumentExceptionthere.- Decoded versus raw.
getPath()decodes%20to a space;getRawPath()does not. Splitting a decoded path on/loses the difference between%2Fand/, so use the raw form for that. - Query parsing is manual.
URIdoes not parsea=1&b=2into a map. Split on&and=and decode each side withURLDecoder. URLEncoderis for form data. It turns spaces into+, which is right forapplication/x-www-form-urlencodedquery values but not for path segments, where a space must be%20.- Equality.
URI.equalscompares the text with some case rules;URL.equalsmay resolve host names, which is slow and can differ over time. resolvereplaces the last segment of the base path: resolvingxagainst/a/bgives/a/x, against/a/b/gives/a/b/x. A query-only reference such as?page=2is a known quirk: Java drops the file name and gives/docs/guide/?page=2.new URL(String)is deprecated since Java 20. Opening aURLstream (openStream()) works forhttp,https,fileandjarbut gives you little control; useHttpClientinstead.- Hosts with underscores are not valid in
getHost(): the URI parses butgetHost()returnsnulland onlygetAuthority()has the text. File.toURI()andPath.toUri()producefile:URIs;Path.of(URI)converts back.
Related
HttpClient, Sockets,PathandPaths, Charsets- Lessons: Networking basics, HTTP client