Quick question -- If I do url processing such as:
try {
URL url = new URI(address).toURL();
InputStream is = url.openStream();
} catch (IOException x) {
. . .
}
is there a way in the catch block to get the http
response code (eg: 404) if there is one?
James Westby - 08 Jan 2006 20:38 GMT
> Quick question -- If I do url processing such as:
>
[quoted text clipped - 7 lines]
> is there a way in the catch block to get the http
> response code (eg: 404) if there is one?
url.openStream() is shorthand for url.openConnection().getInputStream().
You need to get the URLConnection to get the response code. Try using
the two separate methods, like
HttpURLConnection connection = (HttpURLConnection) url.getConnection();
InputStream is = connection.getInputStream();
You can then use connection.getResponseCode() to get the response code
and use the fields of HttpURLConnection to determine which code you have.
James
James Westby - 08 Jan 2006 20:45 GMT
>> Quick question -- If I do url processing such as:
>>
[quoted text clipped - 20 lines]
>
> James
Apologies, that should be
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream is = connection.getInputStream();
James
Larry Coon - 09 Jan 2006 01:01 GMT
> Apologies, that should be
>
> HttpURLConnection connection = (HttpURLConnection)url.openConnection();
> InputStream is = connection.getInputStream();
That was exactly what I needed -- thanks!
Larry Coon
University of California
Thomas Hawtin - 08 Jan 2006 20:53 GMT
> Quick question -- If I do url processing such as:
>
[quoted text clipped - 7 lines]
> is there a way in the catch block to get the http
> response code (eg: 404) if there is one?
If you use URL.openConnection, it shouldn't actually connect straight
away. Cast the URLConnection to HttpURLConnection (assuming you had an
http or https URL). When you use the connection you might get an
exception (the exact behaviour changed at some point, IIRC), but still
have access to the original connection object.
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/