URI Components And Relative Resolution

Read URI components, resolve relative references, and normalize dot segments without string concatenation or manual path parsing.

JavaData Fetching

Code

snippet
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

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:`.