如何从服务器请求中获取文件名?

how to get file name from the server request?

我正在尝试 http 请求并创建到服务器的 http get 请求。服务器必须 return .zip 文件。这是代码:

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

然后我想像这样将它写入文件:

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

但是要创建文件输出流,我想使用服务器提供的文件名。我发现服务器答案有文件名,所有结构如下所示:

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)

如何获取文件名?

你看过HttpURLConnection提供的方法了吗?

尤其是那些涉及headers?

如果你有 servletRequest 对象(比如说 obj)那么 我认为这会有所帮助

obj.getRequestURL() ;

您可以使用HttpUrlConnectionobject的getHeaderField()方法来阅读Content-Dispositionheader。还要确保在不存在的情况下处理。