简体   繁体   中英

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()));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM