Getting http response code

L

Larry Coon

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?
 
J

James Westby

Larry said:
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?


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
 
J

James Westby

James said:
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

Apologies, that should be


HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream is = connection.getInputStream();

James
 
T

Thomas Hawtin

Larry said:
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?

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
 
L

Larry Coon

James said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,157
Latest member
MercedesE4
Top