首页 > 解决方案 > 从 href-attribute 获取 HTTP URL(链接的所有可能方式)

问题描述

我正在尝试做一个简单的脚本,它将任何可能的 HTML 链接转换为 HTTP URL,例如

http://example.com //example.com /index.html ./index.html index.html

我已经尝试过在另一个答案中找到的功能:

public static Integer isAbsoluteURL (String url) throws java.net.MalformedURLException {
    final URL baseHTTP = new URL("http://example.com");
    final URL baseFILE = new URL("file:///");
    if (url.length() > 0) {
        if (url.substring(0, 1) == "/") {
            return 0;
        }
    }
    URL frelative;
    URL hrelative;
    try {
        frelative = new URL(baseFILE, url);
        hrelative = new URL(baseHTTP, url);
    } catch (MalformedURLException e) {
        System.out.println("MalformedURLException found");
        return 3;
    }
    if (frelative.equals(hrelative)) {
        return 0;
    } else {
        return 1;
    }
}

我想获得绝对链接,但代码不适用于 ./, //(没有 http[s])。

谢谢。

标签: javahtmlurl

解决方案


我更喜欢使用 spring 的 UriComponentBuilder 来处理所有事情:

 https://www.baeldung.com/spring-uricomponentsbuilder

推荐阅读