My application processes URLs entered manually by users. I have discovered that some of malformed URLs (like 'http:/not-valid') result in NullPointerException thrown when connection is being opened. As I learned from this Java bug report, the issue is known and will not be fixed. The suggestion is to use java.net.URI, which is "more RFC 2396-conformant".
Question is: how to use URI to work around the problem? The only thing I can do with URI is to use it to parse string and generate URL. I have prepared following program:
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();
}
}
}
Here are results of my tests (with java 1.6.0_20), not much different from what I get with java.net.URL:
sh-3.2$ java Test url-not-valid java.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-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: 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-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)