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
URLConnection throws a FileNotFoundException. How do I discover this was caused by a 404?
-
01-06-2022 - |
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
?
Solution
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