Retrieve filename from http download file

download, filenames, http, java

Solution

GET /downloads/latest.php?product=Foxit-Reader HTTP/1.1

gives a response of `HTTP/1.1 302 Found`

and sets the response header

Location: http://cdn04.foxitsoftware.com/pub/foxit/reader/desktop/win/5.x/5.4/enu/FoxitReader544.11281_enu_Setup.exe

and finally, you issue,

GET /pub/foxit/reader/desktop/win/5.x/5.4/enu/FoxitReader544.11281_enu_Setup.exe HTTP/1.1

That is where the filename seems to be coming from. So, if the redirection is happening transparently, you could still probably get the filename from the request parameter.

Problem

I am trying to download a file from a webserver and save it under the original filename the server is sending with the file. Downloading works very well, but I am not able to get the real filename. For real example I am trying to download this file (Foxit PDF Reader). If I am using this link in a browser like Chrome the browser downloads the file with a exact name including version etc. Where do I get this name from? I tried reading the header informations and was searching for `Content-Disposition` but the server doesn't send this information. Where do I get the exact filename from? I tried something like this: ``` try { URL webfile = new URL("http://www.foxitsoftware.com/downloads/latest.php?product=Foxit-Reader"); URLConnection con = webfile.openConnection(); Map map = con.getHeaderFields(); Set set = map.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (IOException ex) { System.out.println("Error: "+ex.getMessage()); } ``` As you can see in the output there is no `Content-Disposition`: ``` null=[HTTP/1.1 200 OK] ETag=["244005-f36d40-4d003f3868000"] Date=[Sat, 08 Dec 2012 12:29:02 GMT] Content-Length=[15953216] Last-Modified=[Tue, 04 Dec 2012 10:01:36 GMT] Content-Type=[application/x-msdos-program] Connection=[close] Accept-Ranges=[bytes] Server=[Apache/2.2.16 (Debian)] ``` So how can I retrieve the exact filename? The link in a browser downloads a file with the name `FoxitReader544.11281_enu_Setup.exe`. Any ideas?!

Original source