我正在尝试 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)
如何获取文件名?
最佳答案
您可以使用 HttpUrlConnection
对象的 getHeaderField()
方法来读取 Content-Disposition header 。还要确保在案件不存在时进行处理。
关于java - 如何从服务器请求中获取文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29622396/