以下是 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&param2=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 的任何部分。

Java 截取网页路径代码示例 - 获取协议、主机、端口、路径、查询字符串、锚点

原文地址: https://www.cveoy.top/t/topic/mOaX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录