在Android中使用DownloadManager从标题获取文件名 [英] Get file name from headers with DownloadManager in Android
问题描述
我正在使用DownloadManager从URL下载视频文件.
I'm using DownloadManager to download video files from a url.
问题是,如果我使用默认文件夹下载文件,则无法在图库中看到视频.
The problem is if I use the default folder to download the file I can not see the video in the galery.
此外,如果我尝试使用此方法:
Also, If I try to use this method:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, 'filename');
在下载之前,我需要知道文件名 .在这种情况下,我不知道.
I need to know the file name before download which in this case, I don't.
而且,我在url中没有文件名.
And also, I don't have the name of the file in the url.
如何从标头中获取文件名并将其传递给setDestinationInExternalPublicDir方法?还有其他选择吗?
How can I do to get the file name from the headers and pass the name to the method setDestinationInExternalPublicDir ? Other alternatives?
推荐答案
万一有人想要实现执行HEAD请求以获取文件名的实现,
In case anyone want an implementation of doing a HEAD request to get the filename:
class GetFileName extends AsyncTask<String, Integer, String>
{
protected String doInBackground(String... urls)
{
URL url;
String filename = null;
try {
url = new URL(urls[0]);
String cookie = CookieManager.getInstance().getCookie(urls[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", cookie);
con.setRequestMethod("HEAD");
con.setInstanceFollowRedirects(false);
con.connect();
String content = con.getHeaderField("Content-Disposition");
String contentSplit[] = content.split("filename=");
filename = contentSplit[1].replace("filename=", "").replace("\"", "").trim();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
}
return filename;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
}
}
这篇关于在Android中使用DownloadManager从标题获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!