Kri*_*son 44 android filenotfoundexception httpurlconnection
我有一个适用于Android 2.x和3.x的Android应用程序,但在Android 4.x上运行时会失败.
问题出在这部分代码中:
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();
Run Code Online (Sandbox Code Playgroud)
当应用程序在Android 4.x上运行时,getInputStream()调用会产生一个FileNotFoundException.当在早期版本的Android上运行相同的二进制文件时,它会成功.URL也适用于Web浏览器和curl.
显然HttpURLConnection,ICS中有些变化.有没有人知道发生了什么变化,和/或修复可能是什么?
ban*_*ing 28
如果服务器返回错误的错误代码(例如,400或401),也可能抛出FileNotFoundException.您可以按如下方式处理:
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...
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么,但手动处理重定向可以解决问题.
connection.setInstanceFollowRedirects(false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36565 次 |
| 最近记录: |