URI Components And Relative Resolution
Read URI components, resolve relative references, and normalize dot segments without string concatenation or manual path parsing.
Code
import java.net.URI;
public class UriComponentsDemo {
public static void main(String[] args) {
URI base = URI.create("https://api.example.com/v1/users?id=7#profile");
System.out.println("scheme: " + base.getScheme());
System.out.println("authority: " + base.getAuthority());
System.out.println("path: " + base.getPath());
System.out.println("query: " + base.getQuery());
System.out.println("fragment: " + base.getFragment());
// resolve:按 RFC 3986 合并相对引用
URI orders = base.resolve("../orders/42?expand=items");
System.out.println("resolved: " + orders);
// normalize:消掉 . 与 .. 路径段
URI messy = URI.create("https://api.example.com/v1/./users/../orders");
System.out.println("normalized: " + messy.normalize());
// relativize 要求 scheme 与 authority 一致
URI target = URI.create("https://api.example.com/v1/orders");
System.out.println("relative: " + base.relativize(target));
System.out.println("absolute: " + orders.isAbsolute() + " opaque: " + orders.isOpaque());
}
}How the snippet works
The working surface is the class UriComponentsDemo and the function main — everything else is wiring.
Using it
The run emits 9 labeled sections — scheme:, authority:, path:, query:, fragment:, resolved:, normalized:, relative:, absolute: — one per step.
Key statements
URI base = URI.create("https://api.example.com/v1/users?id=7#profile");
URI messy = URI.create("https://api.example.com/v1/./users/../orders");
URI target = URI.create("https://api.example.com/v1/orders");
Interactive Tools for This Topic
SVG to Data URI EncoderMinify SVG markup into UTF-8 and Base64 data URIs with ready-to-use CSS background snippets, live image previews, and exact byte savings statistics.TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.
FAQ
- What does URI Components And Relative Resolution print when run?
- Run it as a complete program — the output lines carry labels such as `scheme:`, `authority:`, `path:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.