FileNotFoundException for HttpURLConnection in Ice

2019-01-08 18:31发布

问题:

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?

回答1:

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

Edit: This is needed when using a POST call.



回答2:

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...
}


回答3:

I Don't know why, but dealing manually with redirection resolves the problem.

connection.setInstanceFollowRedirects(false);


回答4:

A little late but you can also verify the accepted content. You can add this line to accept all kinds of contents

urlConnection.setRequestProperty("Accept","*/*");