← 中文资源

简体中文版本

URI 组件与相对解析

解析 URI 各组件并用 resolve 合并相对引用、normalize 消除点段:不靠字符串拼接也能安全构造请求地址。

阅读英文原文

实现说明

实现都写在 UriComponentsDemo和函数 main里。

使用要点

  • 跑完文件,输出里会留下标记——scheme:、authority:、path:。

常见问题

运行「URI 组件与相对解析」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 scheme:、authority:、path: 标签标明各步骤。

核心语句

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");

代码示例

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());
    }
}