I am trying to create a java console app which will download a file from a URL. The file is created at Runtime and I don't know the file name. When I copy and paste the URL in the browser the save file pop up comes up to save the file. Now I want to create Java code which logs on to the server (validates user I have that done) go to that URL and download the file.
-
Sorry My question is how to implement this. I wrote code like below and when I run it it returns the HTML code instead of the actual .xlsx file. I need to change the code so that when the URL is accessed by my app. The report will be generated and returned at which point I will save the file to the local machineMohamed– Mohamed2012-06-13 16:34:39 +00:00Commented Jun 13, 2012 at 16:34
-
As one might expect, there have been many questions about how to programmatically download files from a server in Java, such as How do you Programmatically Download a Webpage in Java. Voting to close this as a duplicate (please feel free to suggest a more canonical duplicate if you know of one).Andrzej Doyle– Andrzej Doyle2012-06-13 16:38:29 +00:00Commented Jun 13, 2012 at 16:38
-
Andrzej that is what I am getting now. What I want is the file that is created when the URL is accessedMohamed– Mohamed2012-06-13 16:40:27 +00:00Commented Jun 13, 2012 at 16:40
Add a comment
|
2 Answers
Sergii's answer is a good start; however, if the website you want to use requires more that a simple download, consider using Apache's HttpClient.
It supports cookies, authentication, URIs as well as URLs, and file upload.
Comments
Simple exapmple from docs, just to put your url insted of http://www.oracle.com/, and change System.out.println(inputLine); to write file on disk.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
4 Comments
Mohamed
Thanks Sergii but this will only return the HTML code at that page.
Andrzej Doyle
@Saned - This code will request a resource from the server, and will then download the stream of bytes that the server sends in response. So if the URL is for an HTML page you'll get HTML; if the URL points at a Zip file you'll get the bytes of that Zip file. I'm not sure what else you could want?
Mohamed
I have made some update the URL points to a form. I changed the code to post to that form. Once the post is completed a file should be generated. I want to download that file.
Sergii Zagriichuk
I've written put YOUR url, it means that you should handle moment of generation file, and put url DYNAMICALLY after file will be generated!