java如何声明uri
声明 URI 的方法
在 Java 中,可以使用 java.net.URI 类来声明和操作 URI(Uniform Resource Identifier)。以下是几种常见的声明方式:
使用字符串构造 URI
URI uri = new URI("https://example.com/path?query=value#fragment");
使用分段构造 URI

URI uri = new URI("https", "example.com", "/path", "query=value", "fragment");
使用 URI 构建器
URI uri = URI.create("https://example.com/path?query=value#fragment");
处理异常
构造 URI 时可能会抛出 URISyntaxException,需要进行异常处理:

try {
URI uri = new URI("https://example.com");
} catch (URISyntaxException e) {
e.printStackTrace();
}
常用方法
声明 URI 后,可以通过以下方法获取其组成部分:
String scheme = uri.getScheme(); // 获取协议(如 "https")
String host = uri.getHost(); // 获取主机名(如 "example.com")
String path = uri.getPath(); // 获取路径(如 "/path")
String query = uri.getQuery(); // 获取查询参数(如 "query=value")
String fragment = uri.getFragment(); // 获取片段(如 "fragment")
编码与解码
对于包含特殊字符的 URI,可以使用 URLEncoder 和 URLDecoder 进行编码和解码:
String encoded = URLEncoder.encode("value with spaces", StandardCharsets.UTF_8);
String decoded = URLDecoder.decode("value%20with%20spaces", StandardCharsets.UTF_8);






