Question

I've got this code:

String buildUrl = DEFAULT_HOST + "/job/" + jobName + "/" + buildNumber + API_PATH;
URLConnection connection = new URL(buildUrl).openConnection();
InputStream is = connection.getInputStream();

If that buildUrl results in a 404 response, that last line throws a FileNotFoundException. But, I want to know that the server returned a 404 because I don't trust that FileNotFoundException always means 404 and I want to do something special when 404s occur.

How do I know when a 404 occurs when using a URLConnection?

Was it helpful?

Solution

first, cast to HttpURLConnection then call connection.connect() instead of getInputStream. Once done, call getResponceCode(). If all is good, then you can get the input stream

OTHER TIPS

If you are ok with a 3rd party library then look at apache commons http client component project. This library has much more user friendly http api than native url connection api in jdk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top