HttpURLConnection下载了文件名 [英] HttpURLConnection downloaded file name
本文介绍了HttpURLConnection下载了文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以获取使用HttpURLConnection下载的文件的名称?
Is it possible to get the name of a file downloaded with HttpURLConnection?
URL url = new URL("http://somesite/getFile?id=12345");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setAllowUserInteraction(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
InputStream is = conn.getInputStream();
在上面的示例中,我无法从URL中提取文件名,但服务器会将文件名以某种方式。
In the example above I cannot extract the file name from the URL, but the server will send me the file name in some way.
推荐答案
你可以使用 HttpURLConnection.getHeaderField(String name)获取 Content-Disposition
标头,通常用于设置文件名:
You could use HttpURLConnection.getHeaderField(String name) to get the Content-Disposition
header, which is normally used to set the file name:
String raw = conn.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.jpg"
if(raw != null && raw.indexOf("=") != -1) {
String fileName = raw.split("=")[1]; //getting value after '='
} else {
// fall back to random generated file name?
}
正如其他答案所指出的那样,服务器可能会返回无效的文件名,但是你可以尝试一下。
As other answer pointed out, the server might return invalid file name, but you could try it.
这篇关于HttpURLConnection下载了文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文