gavin
gavin

Reputation: 41

I'm getting a FileNotFoundException while trying to httpcon.getInputStream(). Is there a way to easily check if it's a 404 webpage?

So in part of my code I'm trying to access a web page, and in the circumstance that the webpage doesn't exist (which I'm testing) I get a FileNotFoundException.

at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)

I really just want to be able to check if it doesn't exists, and if it doesn't I wouldn't bother with the getInputStream or BufferedReader or whatever. Is there a simple IF clause that would satisfy this?

oracle = new URL(scholarURL);   

HttpURLConnection httpcon = (HttpURLConnection) oracle.openConnection(); 
httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); 

BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));

Upvotes: 0

Views: 318

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

Before getting the InputStream, simply retrieve the status code.

if (con.getResponseCode() == 404) {
    // do something
    InputStream err = con.getErrorStream();
    // use it
}

Note how you should be using UrlConnection#getErrorStream() in case of an error (well non-2xx status code).

Also, seriously consider using a different, better HTTP client. I suggest Apache's HttpComponents.

Upvotes: 3

Related Questions