冰淇淋三明治中HttpURLConnection的FileNotFoundException

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中有些变化.有没有人知道发生了什么变化,和/或修复可能是什么?

reu*_*cam 96

尝试删除setDoOutput调用.摘自这篇博客: 博客

编辑:使用POST调用时需要这样做.

  • +1000谢谢!我正在构建一个用于访问后端的库.我花了几个小时试图找出为什么URLConnections可以从命令行工作,但不是当我将库加载到我的Android项目时. (3认同)
  • 请注意,在发出POST请求时需要这样做!在这种情况下,它应该保持到位. (3认同)
  • 这个答案至少让我节省了一个小时.我的第一个谷歌搜索给了我这个:) (2认同)

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)

  • 我得到了响应代码500,因为我没有设置`Content-Type`,谢谢你指出在这些情况下可能会抛出这个异常. (2认同)

Kir*_*kov 5

我不知道为什么,但手动处理重定向可以解决问题.

connection.setInstanceFollowRedirects(false);
Run Code Online (Sandbox Code Playgroud)