简体   繁体   中英

Downloading a file created in server using Java

I am trying to download a file from a given URL. The URL is not a direct file URL. When this URL is provided in browser manually, we get a prompt for download/save.

For example, http://www.my-domain.com/download/type/salary/format/excel

I have no issues in the URL which has the file name directly in the URL. In the above URL, based on the format and type, server generates the file.

In Java I am trying to download the file using the below code. The file is created, but the content is just the domain content and not the actual excel data.

URL url = new URL("http://www.my-domain.com/download/type/salary/format/excel");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

float totalDataRead = 0;
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream("c:\\test.xls");
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

byte[] data = new byte[1024];
int i = 0;

while ((i = in.read(data, 0, 1024)) >= 0) {
    totalDataRead = totalDataRead + i;
    bout.write(data, 0, i);
}

bout.close();
in.close();

The content is whatever the server sent for that URL. You can't do anything about that from the client end. If it contained Javascript for example it won't get executed.

When you want to solve a problem you have to use the adequate tools to get the thing done. The adequate tools can be found at poi.apache.org.
Have a look at Apache POI .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM