Java URI Class
The Java URI class (java.net.URI) represents a Uniform Resource Identifier: a string that names or locates a resource, such as https://example.com/docs, mailto:info@example.com or urn:isbn:9780134685991. URI parses and checks the address strictly, and it never touches the network.
You use URI to validate addresses, read their parts, join relative links to a base address, and build URLs safely. It is also what HttpClient and the Path API expect, and the recommended way to create a URL.
URI vs URL vs URN
These three terms are often mixed up. A URI is the general idea; a URL and a URN are two kinds of URI.
| Term | Meaning | Example |
|---|---|---|
| URI | Any identifier for a resource | All examples below |
| URL | A URI that says where a resource is and how to get it | https://example.com/report.pdf |
| URN | A URI that gives a resource a permanent name | urn:isbn:9780134685991 |
In Java, the two classes have different jobs:
java.net.URI | java.net.URL | |
|---|---|---|
| Purpose | Parse, check, compare and combine identifiers | Open a connection and read a resource |
| Relative addresses | Supported (../images/logo.png) | Not supported |
| Network access | Never | openStream(), openConnection() |
equals() | Pure text comparison | May do a DNS lookup |
| Convert | uri.toURL() | url.toURI() |
Note: A good rule: keep addresses as
URIobjects in your program, and convert toURLonly when you need to open a connection. The Java URL class lesson covers theURLside.
How to Create a URI in Java
There are three ways to create a URI.
| Way | Invalid input | Use it when |
|---|---|---|
URI.create(String) | Throws unchecked IllegalArgumentException | The address is fixed in your code |
new URI(String) | Throws checked URISyntaxException | The address comes from users or files |
new URI(scheme, userInfo, host, port, path, query, fragment) | Encodes illegal characters for you | You build an address from separate parts |
import java.net.URI;
import java.net.URISyntaxException;
public class CreateUri {
public static void main(String[] args) {
// 1. URI.create: short, for addresses you know are valid
URI home = URI.create("https://gocourse.example.com/java/");
System.out.println("create(): " + home);
// 2. new URI(String): forces you to handle bad input
String userInput = "https://example.com/my report.pdf";
try {
URI fromUser = new URI(userInput);
System.out.println("Parsed: " + fromUser);
} catch (URISyntaxException e) {
System.out.println("Invalid: " + e.getReason() + " at index " + e.getIndex());
}
// 3. Multi-argument constructor: encodes the space for you
try {
URI built = new URI("https", "example.com", "/my report.pdf", null);
System.out.println("Built : " + built);
} catch (URISyntaxException e) {
System.out.println("Unexpected: " + e.getMessage());
}
}
}
Output:
create(): https://gocourse.example.com/java/
Invalid: Illegal character in path at index 22
Built : https://example.com/my%20report.pdf
How it works:
URI.create()is a shortcut fornew URI(...)that wraps the checked exception in anIllegalArgumentException.- The space in
my report.pdfis illegal in a URI.new URI(String)throwsURISyntaxException, whosegetReason()andgetIndex()say what is wrong and where. - The constructor
new URI(scheme, host, path, fragment)treats each argument as plain text and percent-encodes illegal characters, so the space becomes%20.
Getting URI Parts with the Java URI Class
URI has a getter for every component. Missing parts return null, and a missing port returns -1.
import java.net.URI;
public class UriParts {
public static void main(String[] args) {
URI uri = URI.create("https://ravi@api.example.com:8443/v1/orders/42?status=paid&sort=date#items");
System.out.println("Scheme : " + uri.getScheme());
System.out.println("UserInfo : " + uri.getUserInfo());
System.out.println("Host : " + uri.getHost());
System.out.println("Port : " + uri.getPort());
System.out.println("Authority: " + uri.getAuthority());
System.out.println("Path : " + uri.getPath());
System.out.println("Query : " + uri.getQuery());
System.out.println("Fragment : " + uri.getFragment());
System.out.println("Absolute : " + uri.isAbsolute());
URI relative = URI.create("images/logo.png");
System.out.println("Relative scheme: " + relative.getScheme()
+ ", host: " + relative.getHost() + ", port: " + relative.getPort()
+ ", absolute: " + relative.isAbsolute());
}
}
Output:
Scheme : https
UserInfo : ravi
Host : api.example.com
Port : 8443
Authority: ravi@api.example.com:8443
Path : /v1/orders/42
Query : status=paid&sort=date
Fragment : items
Absolute : true
Relative scheme: null, host: null, port: -1, absolute: false
How it works:
- A URI is absolute when it has a scheme (
https).images/logo.pnghas none, so it is relative and its scheme, host and port are empty. - Unlike
URL,URIhappily stores relative addresses; you combine them with a base later usingresolve().
Decoded vs Raw Getters
Each text getter has a raw twin. The normal getter decodes %xx sequences; the raw getter returns the text exactly as written.
import java.net.URI;
public class RawGetters {
public static void main(String[] args) {
URI uri = URI.create("https://example.com/files/annual%20report%202025.pdf?title=Q1%20%26%20Q2");
System.out.println("getPath() : " + uri.getPath());
System.out.println("getRawPath() : " + uri.getRawPath());
System.out.println("getQuery() : " + uri.getQuery());
System.out.println("getRawQuery() : " + uri.getRawQuery());
}
}
Output:
getPath() : /files/annual report 2025.pdf
getRawPath() : /files/annual%20report%202025.pdf
getQuery() : title=Q1 & Q2
getRawQuery() : title=Q1%20%26%20Q2
How it works:
getPath()decodes%20to a space, which is handy for showing a file name to a user.getQuery()decodes%26to&. That makestitle=Q1 & Q2look like two parameters, so when you split a query into parameters, always split the raw query first and decode each value afterwards.
Hierarchical and Opaque URIs
Most URIs are hierarchical: after the scheme they have //, an authority and a path, like web addresses. Some are opaque: the part after the scheme has no inner structure, like email links and URNs.
import java.net.URI;
public class OpaqueUris {
public static void main(String[] args) {
URI[] uris = {
URI.create("https://example.com/contact"),
URI.create("mailto:support@example.com"),
URI.create("urn:isbn:9780134685991"),
URI.create("tel:+91-44-1234-5678")
};
for (URI uri : uris) {
System.out.printf("%-30s opaque=%-5s scheme=%-6s ssp=%s%n",
uri, uri.isOpaque(), uri.getScheme(), uri.getSchemeSpecificPart());
}
}
}
Output:
https://example.com/contact opaque=false scheme=https ssp=//example.com/contact
mailto:support@example.com opaque=true scheme=mailto ssp=support@example.com
urn:isbn:9780134685991 opaque=true scheme=urn ssp=isbn:9780134685991
tel:+91-44-1234-5678 opaque=true scheme=tel ssp=+91-44-1234-5678
How it works:
getSchemeSpecificPart()returns everything between the scheme and the fragment.- For opaque URIs,
getHost()andgetPath()returnnull, because the text after the scheme is not split into parts. Read the scheme-specific part instead.
Resolving Relative Links with resolve()
Web pages are full of relative links like ../css/style.css. resolve() combines a base URI with a relative one, exactly as a browser does.
import java.net.URI;
public class ResolveDemo {
public static void main(String[] args) {
URI page = URI.create("https://gocourse.example.com/java/networking/uri-class.html");
String[] links = {
"url-class.html", // same folder
"../threads/intro.html", // one folder up
"/about", // from the site root
"?page=2", // same page, new query
"#examples", // same page, a section
"https://dev.java/learn/" // already absolute
};
for (String link : links) {
System.out.printf("%-24s -> %s%n", link, page.resolve(link));
}
}
}
Output:
url-class.html -> https://gocourse.example.com/java/networking/url-class.html
../threads/intro.html -> https://gocourse.example.com/java/threads/intro.html
/about -> https://gocourse.example.com/about
?page=2 -> https://gocourse.example.com/java/networking/?page=2
#examples -> https://gocourse.example.com/java/networking/uri-class.html#examples
https://dev.java/learn/ -> https://dev.java/learn/
How it works:
- A relative path replaces the last segment of the base path (
uri-class.html), sourl-class.htmllands in the same folder. ..moves one folder up, and a path starting with/starts again from the site root.- An absolute link is returned unchanged.
- Java's
resolve()follows the older RFC 2396 rules, so a query-only link (?page=2) drops the file name. Browsers keep it (uri-class.html?page=2); if that matters, add the query to the full path yourself.
Note: The base matters:
https://site.com/docs(no trailing slash) treatsdocsas a file, whilehttps://site.com/docs/treats it as a folder. Resolvingintro.htmlgives/intro.htmland/docs/intro.htmlrespectively.
Cleaning and Comparing URIs: normalize(), relativize(), equals()
| Method | What it does |
|---|---|
normalize() | Removes . and .. segments from the path |
relativize(other) | The reverse of resolve(): the relative path from this URI to other |
equals(other) | Compares two URIs; scheme and host are compared without case |
compareTo(other) | Orders URIs, so they can be sorted |
import java.net.URI;
import java.util.List;
import java.util.TreeSet;
public class NormalizeCompare {
public static void main(String[] args) {
URI messy = URI.create("https://example.com/docs/./guide/../api/index.html");
System.out.println("normalize : " + messy.normalize());
URI base = URI.create("https://example.com/docs/");
URI page = URI.create("https://example.com/docs/api/index.html");
System.out.println("relativize: " + base.relativize(page));
URI upper = URI.create("HTTPS://Example.COM/Docs");
URI lower = URI.create("https://example.com/Docs");
URI otherPath = URI.create("https://example.com/docs");
System.out.println("scheme/host case ignored: " + upper.equals(lower));
System.out.println("path case matters : " + lower.equals(otherPath));
// URIs are Comparable, so a TreeSet keeps them sorted and unique
TreeSet<URI> sitemap = new TreeSet<>(List.of(
URI.create("https://example.com/contact"),
URI.create("https://example.com/about"),
URI.create("https://example.com/blog/java"),
URI.create("https://example.com/about")));
System.out.println("sitemap : " + sitemap);
}
}
Output:
normalize : https://example.com/docs/api/index.html
relativize: api/index.html
scheme/host case ignored: true
path case matters : false
sitemap : [https://example.com/about, https://example.com/blog/java, https://example.com/contact]
How it works:
normalize()removes./and cancelsguide/.., leaving the shortest equivalent path. Normalize addresses before comparing or storing them.relativize()returnsapi/index.html, andbase.resolve("api/index.html")would give the full address back.- Scheme and host names are case-insensitive on the web, so
URI.equals()ignores their case. Paths can be case-sensitive, so/Docsand/docsare different. - Because
URIimplementsComparable, aTreeSetsorts the addresses and drops the duplicate/about.
Converting Between URI, URL and Path
URI is the bridge between the networking and file APIs.
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
public class ConvertUri {
public static void main(String[] args) throws Exception {
// URI <-> URL
URI apiUri = URI.create("https://api.example.com/v1/users");
URL apiUrl = apiUri.toURL();
URI backToUri = apiUrl.toURI();
System.out.println("URL : " + apiUrl.getHost() + apiUrl.getPath());
System.out.println("Same after round trip: " + apiUri.equals(backToUri));
// Path <-> URI (file: scheme)
Path report = Path.of("/home/asha/reports/sales 2025.csv");
URI fileUri = report.toUri();
System.out.println("file URI : " + fileUri);
System.out.println("back to Path: " + Path.of(fileUri));
// Non-ASCII characters: toASCIIString() percent-encodes them
URI tamil = new URI("https", "example.com", "/வணக்கம்", null);
System.out.println("toString : " + tamil);
System.out.println("toASCIIString : " + tamil.toASCIIString());
}
}
Output:
URL : api.example.com/v1/users
Same after round trip: true
file URI : file:///home/asha/reports/sales%202025.csv
back to Path: /home/asha/reports/sales 2025.csv
toString : https://example.com/வணக்கம்
toASCIIString : https://example.com/%E0%AE%B5%E0%AE%A3%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%AE%E0%AF%8D
How it works:
toURL()andtoURI()convert in both directions without losing information.Path.toUri()builds afile:URI and encodes the space;Path.of(URI)turns it back into a path. On Windows the URI looks likefile:///C:/Users/....toString()keeps non-ASCII characters as they are.toASCIIString()encodes them as UTF-8 bytes in%xxform, which is what you must send over HTTP.
Real-World Example: A Safe API URL Builder
Apps that call REST APIs build many URLs from a base address, path segments and query parameters. Gluing strings together breaks as soon as a value contains a space, / or &. This small builder encodes every piece correctly and returns a URI ready for HttpClient. It also parses a query string back into a map.
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ApiUrlBuilder {
private final URI baseUri;
private final List<String> pathSegments = new ArrayList<>();
private final Map<String, String> queryParams = new LinkedHashMap<>();
private ApiUrlBuilder(String base) {
this.baseUri = URI.create(base.endsWith("/") ? base : base + "/");
}
static ApiUrlBuilder from(String base) {
return new ApiUrlBuilder(base);
}
ApiUrlBuilder path(Object segment) {
pathSegments.add(encode(segment.toString()).replace("+", "%20")); // spaces in paths are %20
return this;
}
ApiUrlBuilder query(String name, Object value) {
queryParams.put(encode(name), encode(value.toString()));
return this;
}
URI build() {
StringBuilder relative = new StringBuilder(String.join("/", pathSegments));
if (!queryParams.isEmpty()) {
relative.append('?');
queryParams.forEach((name, value) -> relative.append(name).append('=').append(value).append('&'));
relative.setLength(relative.length() - 1); // remove the last &
}
return baseUri.resolve(relative.toString());
}
static Map<String, String> parseQuery(URI uri) {
Map<String, String> params = new LinkedHashMap<>();
if (uri.getRawQuery() == null) return params;
for (String pair : uri.getRawQuery().split("&")) { // split the RAW query
String[] parts = pair.split("=", 2);
params.put(decode(parts[0]), parts.length > 1 ? decode(parts[1]) : "");
}
return params;
}
private static String encode(String text) {
return URLEncoder.encode(text, StandardCharsets.UTF_8);
}
private static String decode(String text) {
return URLDecoder.decode(text, StandardCharsets.UTF_8);
}
public static void main(String[] args) {
URI search = ApiUrlBuilder.from("https://api.shop.example.com/v2")
.path("stores").path("Chennai Central").path("products")
.query("q", "laptop & bag")
.query("maxPrice", 55000)
.query("sort", "price/asc")
.build();
System.out.println(search);
System.out.println("Host : " + search.getHost());
System.out.println("Path : " + search.getPath());
parseQuery(search).forEach((name, value) -> System.out.println(" " + name + " = " + value));
URI order = ApiUrlBuilder.from("https://api.shop.example.com/v2/").path("orders").path(1042).build();
System.out.println(order);
}
}
Output:
https://api.shop.example.com/v2/stores/Chennai%20Central/products?q=laptop+%26+bag&maxPrice=55000&sort=price%2Fasc
Host : api.shop.example.com
Path : /v2/stores/Chennai Central/products
q = laptop & bag
maxPrice = 55000
sort = price/asc
https://api.shop.example.com/v2/orders/1042
How it works:
- A folder-style base. The constructor makes sure the base ends with
/, soresolve()adds the path under/v2/instead of replacingv2. Both"/v2"and"/v2/"work. - Encoding path segments. Each segment is encoded with
URLEncoder, and+is changed to%20, because+means a space only in query strings. A/inside a segment would be encoded as%2F, so it cannot create extra folders. - Encoding query parameters. Names and values are encoded separately, so
&inlaptop & bagbecomes%26and/inprice/ascbecomes%2F. ALinkedHashMapkeeps the parameters in the order they were added. - Building.
build()joins the pieces into a relative URI and resolves it against the base, which also validates the result. - Parsing back.
parseQuery()splits the raw query on&and=before decoding, so encoded&characters inside values never split a parameter in two.
The URI this builder returns can be passed straight to HttpRequest.newBuilder(uri), as shown in the Java HttpClient lesson and in Java networking basics.