我正在编写Android应用程序,以便从网站上下载特定文件(目前为20M Byte)以进行测试。我使用URLConnection和BufferedInputStream。 下载几个Mega Bytes后,我收到IOException Connection Reset By Peer。 inputStream.read()暂停大约130秒,然后引发异常。 从几次尝试,我注意到下载的字节是11,272,192或11,010,048,知道该文件可以正常从PC下载。 以下是我使用的代码段:
@Override
protected String doInBackground(String... f_url) {
try {
URL url = new URL(f_url[0]);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.setConnectTimeout(5000);
conection.setReadTimeout(5000);
conection.setDoOutput(false);
conection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
...
do {
byte data[] = new byte[1024];;
if (((count = input.read(data)) == -1)) {
break;
}
sum+=count;
...
} while (true);
input.close();
conection.disconnect();
} catch (Exception e) {
...
}
return null;
}
我想知道导致这个问题的原因,以及如何避免这个问题。 我读了多个(类似主题)问题,但没有帮助。他们都同意代码没有问题,而且是网络(或主机)问题。但我需要知道为什么下载失败以及如何克服它 知道
当服务器通过发送RST数据包关闭连接时,会发生由对等错误引起的连接重置。服务器可以执行此操作的原因很多 - 您可能使用了太多资源,因此可能会关闭连接,可能会出现一些错误。服务器配置等。我有同样的错误所以我将缓冲区大小从1024更改为512并且它工作。我认为它工作,因为这减少了服务器必须使用的资源。还将input.read(data)更改为input.read (数据,0512)。