我的应用程序处理用户手动输入的URL。我发现一些格式不正确的URL(比如'http:/not-valid')在打开连接时会导致NullPointerException异常。从这个Java bug报告中了解到,该问题已知并且不会被修复。建议使用java.net.URI,它更符合RFC 2396标准。
问题是:如何使用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-valid java.lang.IllegalArgumentException: URI不是绝对URI at java.net.URI.toURL(URI.java:1080) at Test.main(Test.java:9) sh-3.2$ java Test http:/url-not-valid java.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-valid java.lang.IllegalArgumentException: 协议 = http 主机 = 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-valid java.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)