使用Android中的DownloadManager从标头中获取文件名

rod*_*eon 7 android android-download-manager

我正在使用DownloadManager从网址下载视频文件.

问题是,如果我使用默认文件夹下载文件,我无法在galery中看到视频.

另外,如果我尝试使用此方法:

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, 'filename');
Run Code Online (Sandbox Code Playgroud)

我需要下载之前知道文件名,在这种情况下,我不知道.

而且,我在网址中没有该文件的名称.

如何从标头中获取文件名并将名称传递给方法setDestinationInExternalPublicDir?其他选择?

rod*_*eon 9

如果有人想要执行HEAD请求来获取文件名:

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) {

    }
}
Run Code Online (Sandbox Code Playgroud)