Reputation: 11
I am trying to download an Attachment from a direct https web URL using Java. eg., https://DNS/secure/attachment/1165147/RegressionTestingPlugin.zip I am able to download the Attachment, but it is Just 2 KB. I have tried many methods, but it doesn't helps. Can you help me in this?
METHOD 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();
METHOD 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();
Upvotes: 1
Views: 641
Reputation: 24
Why reinvent the wheel, try apache commons io package. It is simple to use. I personally use the following API to download files locally . (@criztovyl , thanks for the suggestion.)
FileUtils.copyURLToFile(source, destination, connectionTimeout, readTimeout);
The code goes below.
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");
}
}
Quick security tip : Also, from your example, if you are trying in production, then please consider using proper hostnameverifier and SSLContext for the httpsurlconnection object.
Upvotes: 0