FileNotFoundException when calling webservice FileNotFoundException when calling webservice android android

FileNotFoundException when calling webservice


The HttpURLConnection class is misleading in that it will throw a FileNotFoundException for any HTTP error code of 400 or above.

So it's not necessarily an incorrect URL (404) it could be 400 (bad request), 403 (forbidden), 500 (internal server error) or something else.

Use the getResponseCode method to get a more precise indication of the problem.


It's the same problem I was having:HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
You should instead use getErrorStream() when the status code is higher than 400.

More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.

Here is an example of how I went to manage it

... connection code code code ...// Get the response code int statusCode = connection.getResponseCode();InputStream is = null;if (statusCode >= 200 && statusCode < 400) {   // Create an InputStream in order to extract the response object   is = connection.getInputStream();}else {   is = connection.getErrorStream();}... callback/response to your handler....

In this way, you'll be able to get the needed response in both success and error cases.

Hope this helps!


Try removing:

connection.setDoInput(true);connection.setDoOutput(true);