Java中截取网页路径的代码
以下是Java中截取网页路径的示例代码:
import java.net.URL;
public class URLDemo {
public static void main(String[] args) throws Exception {
String urlString = "https://www.example.com/path/to/page.html";
URL url = new URL(urlString);
String protocol = url.getProtocol(); // 获取协议名,例如:https
String host = url.getHost(); // 获取主机名,例如:www.example.com
int port = url.getPort(); // 获取端口号,如果没有指定则返回-1
String path = url.getPath(); // 获取路径,例如:/path/to/page.html
String query = url.getQuery(); // 获取查询字符串,例如:param1=value1¶m2=value2
String ref = url.getRef(); // 获取锚点,例如:section1
System.out.println("Protocol: " + protocol);
System.out.println("Host: " + host);
System.out.println("Port: " + port);
System.out.println("Path: " + path);
System.out.println("Query: " + query);
System.out.println("Ref: " + ref);
}
}
在上面的示例中,我们使用java.net.URL类来解析URL字符串,并使用getProtocol()、getHost()、getPort()、getPath()、getQuery()和getRef()方法来获取URL的各个部分。在这个例子中,我们打印出了协议名、主机名、端口号、路径、查询字符串和锚点。您可以根据需要修改代码来截取URL的任何部分。
原文地址: https://www.cveoy.top/t/topic/blNR 著作权归作者所有。请勿转载和采集!