我正在尝试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);
}
但是要创建fileoutputstream,我想使用服务器提供的文件名。我发现服务器答案具有文件名,所有结构如下所示:
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标头。另外,请确保在不存在的情况下处理此情况。