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

Java 如何从服务器请求中获取文件名?,java,httprequest,server,Java,Httprequest,Server,我正在尝试http请求并创建对服务器的http get请求。服务器必须返回.zip文件。代码如下: url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); is = conn.getInputStream(); 然后我想像这样将其写入文件: r = 1; whil

我正在尝试http请求并创建对服务器的http get请求。服务器必须返回.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)
但要创建fileoutputstream,我想使用服务器提供的文件名。我发现server answer具有文件名,所有结构如下所示:

    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)

如何获取文件名?

您看过提供的方法了吗


特别是那些涉及
头的

如果你有servletRequest对象(比如obj),那么 我想这会有帮助的

obj.getRequestURL() ;

您可以使用
HttpUrlConnection
对象的
getHeaderField()
方法来读取内容处置头。另外,请确保在不存在的情况下处理该案例。

是的,我找到了这个。但是除了String contentDisposition=conn.getHeaderField(“contentDisposition”);还有什么好看的方法可以获取文件名吗;int fileNamePosition=contentDisposition.lastIndexOf(“文件名”);字符串文件名=contentDisposition.substring(fileNamePosition+9)@NikitinMikhail这是唯一的方法,而且看起来也不会很糟糕。String filename=conn.getHeaderField(“内容处置”).split(“filename=”)[1]。trim();