Good day.

How can I download a file by url, getting its parameters in the form of a name and extension?

All the examples found make a stream entry to an already created file with the specified name and extension.

thank

  • You need to parse the page. then get the file names and then download. So? - Saidolim
  • No, the user in the form gives a link to the file, I need to get it, recognize the format and save it. - dzrock
  • one
    I now use this hc.apache.org for downloading from http-servers. Recognize the format will help http headers, if the server will give them along with the file. Otherwise, spin yourself as you wish. You can search how different browsers are managed with this case. Once came across a description for chrome. - Sergey

1 answer 1

In fact, the concept of extension came from Windows. In Linux, the file name includes what is after the dot too. You can get the file name if the server included it in Content-Disposition . Well, at least the HTTP standard says that this information is there. Content-Disposition can be taken as follows:

 String uri = "http://www.website.com/download/file.pdf"; URL url = new URL(uri); URLConnection conn = url.openConnection(); Map header =conn.getHeaderFields(); header.get("Content-Disposition") 

The problem is that not everyone does it. For example, Google Drive on the download command in Content-Disposition returns json.txt, which has file instructions. It looks like this:

 disposition: "SCAN_CLEAN" downloadUrl: "https://doc-10-bc-docs.googleusercontent.com/docs/securesc/xxxxxxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxxxx?e=download" fileName: "Oxford_dictionary.zip" scanResult: "OK" sizeBytes: 431943 

There is in the header more Content-Type . From it, you can extract a separate extension (more precisely, the media type) of the file. You need to take something like this:

 String uri = "http://www.website.com/download/file.pdf"; URL url = new URL(uri); URLConnection conn = url.openConnection(); String type = conn.getContentType(); 

It returns a string like:

 application/pdf 

But something standard, as far as I know, no.

  • Thanks for the detailed answer! - dzrock