java.io.IOException:尝试下载文件时,远程主机强行关闭了现有连接



我正在尝试从https://网址下载一个使用 Java 的文件,但它一直向我返回此错误:

java.io.IOException:现有连接被 远程主机

这是我正在使用的代码:

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);
}

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

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

虽然它是低级别的 IO,但它在不使用第三方依赖项的情况下对我有用:

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);
}
}

最新更新