如何从服务器请求中获取文件名? [英] how to get file name from the server request?

查看:96
本文介绍了如何从服务器请求中获取文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
   }

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

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)

如何获取文件名?

推荐答案

您可以使用 HttpUrlConnection 对象的 getHeaderField()方法读取Content-Disposition标头.另外,请确保在不存在的情况下也可以处理.

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.

这篇关于如何从服务器请求中获取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆