gpt4 book ai didi

java - 如何验证 URL 在 Java 1.6 中是否有效?

转载 作者:搜寻专家 更新时间:2023-11-01 03:29:55 25 4
gpt4 key购买 nike

我的应用程序处理用户手动输入的 URL。我发现某些格式错误的 URL(如“http:/not-valid”)会导致在打开连接时抛出 NullPointerException。正如我从 this Java bug report 中了解到的那样,该问题是已知的,不会被修复。建议使用 java.net.URI,它“更符合 RFC 2396”。

问题是:如何使用 URI 解决这个问题?我唯一能用 URI 做的就是用它来解析字符串并生成 URL。我准备了以下程序:

import java.net.*;

public class Test
{
public static void main(String[] args)
{
try {
URI uri = URI.create(args[0]);
Object o = uri.toURL().getContent(); // try to get content
}
catch(Throwable e) {
e.printStackTrace();
}
}
}

这是我的测试结果(使用 java 1.6.0_20),与我使用 java.net.URL 得到的结果没有太大区别:

sh-3.2$ java Test url-not-validjava.lang.IllegalArgumentException: URI is not absolute        at java.net.URI.toURL(URI.java:1080)        at Test.main(Test.java:9)sh-3.2$ java Test http:/url-not-validjava.lang.NullPointerException        at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:795)        at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)        at java.net.URLConnection.getContent(URLConnection.java:688)        at java.net.URL.getContent(URL.java:1024)        at Test.main(Test.java:9)sh-3.2$ java Test http:///url-not-validjava.lang.IllegalArgumentException: protocol = http host = null        at sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:151)        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:796)        at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)        at java.net.URLConnection.getContent(URLConnection.java:688)        at java.net.URL.getContent(URL.java:1024)        at Test.main(Test.java:9)sh-3.2$ java Test http:////url-not-validjava.lang.NullPointerException        at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:795)        at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)        at java.net.URLConnection.getContent(URLConnection.java:688)        at java.net.URL.getContent(URL.java:1024)        at Test.main(Test.java:9)

最佳答案

您可以使用 appache Validator Commons ..

UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://google.com");

http://commons.apache.org/validator/

http://commons.apache.org/validator/api-1.3.1/

关于java - 如何验证 URL 在 Java 1.6 中是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3138941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com