how to get file name from the server request?

跟風遠走 提交于 2019-12-24 03:53:15

问题


I'm trying http requests and create http get request to server. Server must return .zip file. here is the code:

        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        is = conn.getInputStream();

then I want to write it to file like this:

    r = 1;
    while(r > 0){
     r = is.read(buf);
     if(r > 0)
    fos.write(buf, 0, r);
   }

but to create fileoutputstream i want to use the file name provided by server. I've found that server answer has the file name and all the structure looks like this:

HTTP/1.1 200 OK
Date: Mon, 07 Apr 2003 14:51:19 GMT
Server: Apache/1.3.20 (Win32) PHP/4.3.0
Last-Modified: Mon, 07 Apr 2003 14:51:00 GMT
Accept-Ranges: bytes
Content-Length: 673
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: application/zip
Content-Disposition: attachment; filename=test.zip
Pragma: no-cache

....(zip content)

how to get filename?


回答1:


You can use the HttpUrlConnection object's getHeaderField() method to read the Content-Disposition header. Also make sure you handle the case when it is not present.




回答2:


Have you had a look at the methods that HttpURLConnection offers?

Especially the ones that involve headers?




回答3:


if u have servletRequest object(lets say obj) then i think this will help

obj.getRequestURL() ;


来源:https://stackoverflow.com/questions/29622396/how-to-get-file-name-from-the-server-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!