Java, “URI can't be null” error on simple HTTP client

℡╲_俬逩灬. 提交于 2020-01-16 05:37:07

问题


I'm trying to write a simple HTTP client that, given an absolute HTTP path, performs a simple HTTP GET request and prints out the content to standard output.

However, I'm getting the following error on any page I try to load:

    java.lang.IllegalArgumentException: URI can't be null.
    at sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:141)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:926)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
    at HTTrack.main(HTTrack.java:68)

The code that is raising the exception is:

try
{
    System.out.println("We will attempt to read " + getfilepath(args[0]) + " from " + getbasesite(args[0]));
    URL serverConnect = new URL("http", getbasesite(args[0]), getfilepath(args[0]));
    con = (HttpURLConnection)serverConnect.openConnection();
    con.setRequestMethod("GET");    
    con.setDoOutput(true);
    con.setReadTimeout(10000);
    System.out.println("Attempting to connect to " + getbasesite(args[0]) + " on port 80...");
    System.out.println("URL = " + con.getURL());
    con.connect();
    //System.out.println("Connection succeeded! Attempting to read remote file " + getfilepath(args[0]));
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line = "";
    while((line = br.readLine()) != null)
    {
        System.out.println(line);
    }

}

The line that is raising the exception (HTTrack.java:68) is the con.connect() line, and the functions getbasesite and getfilepath return the server host name and remote file paths of a URL, respectively.

For example if passed the string http://www.somesite.com/somepage.html, getbasesite will return "www.somesite.com" and getfilepath will return "/somepage.html". I know the HttpURLConnection is being passed these values correctly because when I call getURL it returns what I expect: http://www.somesite.com/somepage.html

I'm stuck as to what might be causing this error - I've tested that the HttpURLConnection class indeed gets the correct URL out of the constructor arguments with the line System.out.println("URL = " + con.getURL());, so I'm not sure why it's failing the attempts to connect with the error that the "URI can't be null".


回答1:


Try removing your con.setDoOutput(true); or setting it to false. That line is telling your connection that you are going to be using it to write output, but then later on you are reading from the stream by calling con.getInputStream().



来源:https://stackoverflow.com/questions/26004977/java-uri-cant-be-null-error-on-simple-http-client

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!