java如何建立url
创建 URL 对象的方法
在 Java 中,可以使用 java.net.URL 类来创建和操作 URL。以下是几种常见的创建 URL 对象的方式:
使用字符串构造 URL
URL url = new URL("https://www.example.com");
指定协议、主机和路径
URL url = new URL("https", "www.example.com", "/path/to/resource");
包含端口号

URL url = new URL("https", "www.example.com", 443, "/path/to/resource");
处理相对 URL
URL baseUrl = new URL("https://www.example.com");
URL relativeUrl = new URL(baseUrl, "relative/path");
处理 URL 创建异常
创建 URL 时可能会抛出 MalformedURLException,需要进行异常处理:

try {
URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
访问 URL 内容
创建 URL 对象后,可以打开连接并读取内容:
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
URL 编码处理
当 URL 包含特殊字符时,需要进行编码处理:
String encodedUrl = URLEncoder.encode("https://www.example.com?param=value with space", "UTF-8");
URL url = new URL(encodedUrl);
解析 URL 各部分
可以从 URL 对象中提取各个组成部分:
URL url = new URL("https://www.example.com:443/path?query=value#fragment");
String protocol = url.getProtocol(); // "https"
String host = url.getHost(); // "www.example.com"
int port = url.getPort(); // 443
String path = url.getPath(); // "/path"
String query = url.getQuery(); // "query=value"
String ref = url.getRef(); // "fragment"






