【问题标题】:HttpURLConnection java.io.FileNotFoundExceptionHttpURLConnection java.io.FileNotFoundException
【发布时间】:2013-04-21 18:31:45
【问题描述】:

如果我连接到看起来像是 Apache 服务器的东西,下面的代码效果很好,但是当我尝试连接到我的 .Net 服务器时,它会引发错误。我猜这是一个标头要求,但无论我尝试什么似乎都无法获得成功的响应。

public String Download(String Url)
{
 String filepath=null;
 try {
  //set the download URL, a url that points to a file on the internet
  //this is the file to be downloaded
  URL url = new URL(Url);
  //create the new connection
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

  //set up some things on the connection
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true); 
   //and connect!
  urlConnection.connect();
  //set the path where we want to save the file
  //in this case, going to save it on the root directory of the sd card.
  File SDCardRoot = Environment.getExternalStorageDirectory();
  //create a new file, specifying the path, and the filename
  //which we want to save the file as.

  String filename= "effortback.png";   // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
  Log.i("Local filename:",""+filename);
  File file = new File(SDCardRoot + "/",filename);

  //=====================================
  if(file.createNewFile())
  {
   file.createNewFile();
  }
  //=====================================

  //this will be used to write the downloaded data into the file we created
  FileOutputStream fileOutput = new FileOutputStream(file);

  //this will be used in reading the data from the internet
  InputStream inputStream = urlConnection.getInputStream();

  //=====================================
  //this is the total size of the file
  int totalSize = urlConnection.getContentLength();
  //variable to store total downloaded bytes
  int downloadedSize = 0;
  //=====================================

  //create a buffer...
  byte[] buffer = new byte[2048];
  int bufferLength = 0; //used to store a temporary size of the buffer

  //now, read through the input buffer and write the contents to the file
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
   //add the data in the buffer to the file in the file output stream (the file on the sd card
   fileOutput.write(buffer, 0, bufferLength);
   //add up the size so we know how much is downloaded
   downloadedSize += bufferLength;
   //this is where you would do something to report the prgress, like this maybe
   Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;

  }
  //close the output stream when done
  fileOutput.close();
  if(downloadedSize==totalSize)   filepath=file.getPath();

 //catch some possible errors...
 } catch (MalformedURLException e) {
  e.printStackTrace();
  Log.i("URL-ERROR:",e.toString());
 } catch (IOException e) {
  filepath=null;
  e.printStackTrace();
  Log.i("IO-ERROR:",e.toString());
 }
 Log.i("filepath:"," "+filepath) ;

 return filepath;

}

错误范围:

java.io.FileNotFoundException  //I always get this with either one of the below
   org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)

//or this one below
libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionTmpl.java:186)

似乎无论我尝试什么,我都无法让它工作。同样,如果我尝试从 Google 或其他一些网站下载图像,它会起作用,但不是全部,但绝对不是我的 (.Net)。我在这里想念什么?请帮忙。

【问题讨论】:

  • 好的,做了一点挖掘,发现我从服务器收到 403 错误。这是一个安全错误,所以现在我的问题是如何克服它?提前致谢。
  • 好的,我想通了。如果您遇到同样的问题,请不要使用此行非常重要,还要检查您的 URL。第一个问题是我的 URL 拼写错误,所以我得到了服务器的明显响应。在我修复了我的 URL 后,它仍然有问题。最终是这一行: urlConnection.setDoOutput(true);显然,JAVA 中的这一行强制 http 协议将 GET 更改为 POST,而不管指定 GET。仅供参考,供未来人士参考。
  • 谢谢,这让我忙了一整天。
  • 谢谢,请回答您自己的问题!
  • @nathan,您应该将其发布为您自己问题的答案并接受它。根据 SO 规则,这完全没问题,之前已经做过很多次了。

标签: android download httpurlconnection filenotfoundexception


【解决方案1】:

如果您的服务器返回>= HTTPStatus.BAD_REQUEST (400),您可以从HttpUrlConnection(和OkHttpClient)获得FileNotFoundException。你应该先检查状态码,看看你需要读什么流。

int status = connection.getResponseCode();

if(status >= HttpStatus.SC_BAD_REQUEST)
    in = connection.getErrorStream();
else
    in = connection.getInputStream();

HttpStatus 已弃用。最新的语法似乎是:

InputStream inputStream;
int status = urlConnection.getResponseCode();

if (status != HttpURLConnection.HTTP_OK)  {
    inputStream = urlConnection.getErrorStream();
}
else  {
    inputStream = urlConnection.getInputStream();
}

【讨论】:

  • 太棒了!真的很有帮助
  • HttpStatus 现已弃用。此答案需要更新。
  • 使用 HttpURLConnection.HTTP_BAD_REQUEST,API 级别 22 已弃用 HTTPStatus.BAD_REQUEST
  • 如何打印参数?
【解决方案2】:

遇到了同样的问题,按照你说的解决了:

urlConnection.setDoOutput(false);

请注意,您必须将其设置为 false,因为默认情况下为 true。
请注意,您必须将其设置为 false,因为 Volley HurlStack 将其设置为 true。
保重 ;)

编辑: 我刚刚检查了代码,默认情况下它是错误的,正如@Abraham Philip 所说。但我必须将其设置为 false,因为如果我调用 getDoOutput(),它会返回 true。我发现 Volley HurlStack 将其设置为 true。所以,我的结论是,setDoOutput 为 false,它会起作用。

package java.net;
public abstract class URLConnection {
...

    /**
     * Specifies whether this {@code URLConnection} allows sending data.
     */
    protected boolean doOutput;

...
    public boolean getDoOutput() {
        return doOutput;
    }

    public void setDoOutput(boolean newValue) {
        checkNotConnected();
        this.doOutput = newValue;
    }

【讨论】:

  • 您的说法似乎不正确。 setDoOutput 默认为 false。参考(Java 文档):download.java.net/jdk7/archive/b123/docs/api/java/net/…
  • 是的,你是对的,默认情况下它是错误的。检查我的更新;)
  • 和 +1,因为你变成了 OP 刚刚提到的评论的答案。
【解决方案3】:

我遇到了一个问题,执行 HEAD-Request 时会抛出 FileNotFoundException
原因是,对HEAD 的响应没有正文,因此对getInputStream 的调用会抛出FileNotFoundException

因此,如果您正在执行HEAD,则不应尝试获取InputStream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多