如何使用Java从直接的web URL下载附件并将其保存在本地机器中



我正在尝试使用Java从直接的https web URL下载附件。例如。,https://DNS/secure/attachment/1165147/RegressionTestingPlugin.zip我可以下载附件,但它只有2KB。我试过很多方法,但都无济于事。你能帮我吗?

方法1

URL url3 = new URL(AttachmentURL);
HttpsURLConnection httpConnection1= (HttpsURLConnection) url3.openConnection();                             
httpConnection1 = (HttpsURLConnection) url3.openConnection();
httpConnection1.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange");
httpConnection1.setRequestProperty("Authorization", "Basic DummyAUTH");
httpConnection1.setRequestProperty("Content-Type", "application/octet-stream");
OutputStream os = new FileOutputStream("C:/IssueIDs/"+AttachmentName, true);
os.close();

方法2

URL url4 = new URL(AttachmentURL);
URLConnection connection = url4.openConnection();
InputStream inputstream = connection.getInputStream();
FileSystemView filesys = FileSystemView.getFileSystemView();
filesys.getHomeDirectory();
BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(new File("C:\IssueIDs\"+AttachmentName)));
byte[] buffer = new byte[1024];
int bytesRead;
while((bytesRead = inputstream.read(buffer)) > 0)
{ 
bufferedoutputstream.write(buffer, 0, bytesRead);
}
bufferedoutputstream.flush();
bufferedoutputstream.close();
inputstream.close();

为什么要重新发明轮子,试试apachecommons-io包。它使用起来很简单。我个人使用以下API在本地下载文件。(@criztovyl,谢谢你的建议。(

FileUtils.copyURLToFile(source, destination, connectionTimeout, readTimeout);

代码如下。

import org.apache.commons.io.FileUtils;
import java.net.URL;
import java.io.File;
import java.util.Date;
class DownloadFile{
public static void main(String[] args) throws Exception{
String fileNameToDownload = "pathToFile"; // https://helloworld.com/file.txt
URL source = new URL(args[0]+fileNameToDownload);
File destination = new File(args[1]+File.separator+fileNameToDownload);
long start = System.currentTimeMillis();
System.out.println("initiated Download at "+new Date(start));
int connectionTimeout = 5*1000;
int readTimeout = 30*60*1000;
FileUtils.copyURLToFile(source, destination, connectionTimeout, readTimeout);
long end = System.currentTimeMillis();
System.out.println("Copleted downloading at "+new Date(end));
System.out.println("Time taken to download file is "+(end-start)/1000+" seconds");
}
}

快速安全提示:此外,根据您的示例,如果您正在生产中尝试,请考虑为httpsurlconnection对象使用适当的hostnameverifier和SSLContext。

最新更新