java.io.IOException:尝试下载文件时,远程主机强行关闭了现有连接 [英] java.io.IOException: An existing connection was forcibly closed by the remote host when trying to download file

查看:949
本文介绍了java.io.IOException:尝试下载文件时,远程主机强行关闭了现有连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java从 https:// 网址下载文件,并且不断向我返回此错误:

I'm trying to download a file using Java from a https:// url and it keeps returning me this error:


java.io.IOException:
远程主机强行关闭了现有连接

java.io.IOException: An existing connection was forcibly closed by the remote host

这是我正在使用的代码:

Here is the code I am using:

URL website = new URL(fileUrl);
File destinationFile = new File(toPath + returnFileNameFromUrl(fileUrl));
FileUtils.copyURLToFile(website, destinationFile);

我已经尝试过这样做:

try (InputStream inputStream = website.openStream();
     ReadableByteChannel rbc = Channels.newChannel(inputStream);
     FileOutputStream fileOutputStream = new FileOutputStream(toPath + returnFileNameFromUrl(fileUrl))) {
     fileOutputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
     }

但是结果是一样的。
我在做什么错了?

But the result was the same. What am I doing wrong?

我已经检查过,可以从Chrome访问URL,并且文件存在。

I already checked, the URL is accesible from Chrome and the file exists.

推荐答案

尽管IO级别较低,但它对我有效,而无需使用第三方依赖项:

Although it is a bit lower level IO, it works for me without using third party dependency:

    URL fileUrl = new URL("http://link.to/a.file");
    File dest = new File("local.file");
    try(InputStream inputStream = fileUrl.openStream();
        FileOutputStream outputStream = new FileOutputStream(dest)){
      byte[] buffer = new byte[64*1024];
      int readBytes;
      while((readBytes = inputStream.read(buffer, 0, buffer.length))!=-1){
        outputStream.write(buffer, 0, readBytes);
      }
    }

这篇关于java.io.IOException:尝试下载文件时,远程主机强行关闭了现有连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆