Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileNotFoundException for HttpURLConnection in Ice Cream Sandwich

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?

like image 231
Kristopher Johnson Avatar asked Feb 20 '12 17:02

Kristopher Johnson


2 Answers

Try removing the setDoOutput call. Taken from this blog: a blog

Edit: This is needed when using a POST call.

like image 119
reuscam Avatar answered Sep 18 '22 15:09

reuscam


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... } 
like image 33
ban-geoengineering Avatar answered Sep 19 '22 15:09

ban-geoengineering