0

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()));
gavin
  • 41
  • 1
  • 1
  • 3

1 Answers1

3

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724