I have an Android app that works fine with Android 2.x and 3.x, but it fails when run on Android 4.x.
The problem is in this section of code:
URL url = new URL("http://blahblah.blah/somedata.xml"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream();
When the application is running on Android 4.x, the getInputStream()
call results in a FileNotFoundException
. When the same binary is running on earlier versions of Android, it succeeds. The URLs also work fine in web browsers and with curl
.
Apparently something about HttpURLConnection
has changed in ICS. Does anybody have any idea what has changed, and/or what the fix might be?
Try removing the setDoOutput call. Taken from this blog: a blog
Edit: This is needed when using a POST call.
A FileNotFoundException may also been thrown if the server returns a bad error code (e.g., 400 or 401). You can handle this as follows:
int responseCode = con.getResponseCode(); //can call this instead of con.connect() if (responseCode >= 400 && responseCode <= 499) { throw new Exception("Bad authentication status: " + responseCode); //provide a more meaningful exception message } else { InputStream in = con.getInputStream(); //etc... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With