Reputation: 21532
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".
Upvotes: 1
Views: 6951
Reputation: 47239
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()
.
Upvotes: 2