在下载管理器请求中设置请求属性



我一直在使用urlconnection后台服务在我的应用程序中下载文件。该请求需要一个令牌,该令牌应传递给服务器才能授予权限。代码工作正常。这是一个片段..

           URL url = new URL(fileURL);
            HttpURLConnection conection = (HttpURLConnection) url.openConnection();
            conection.setRequestMethod("GET");
            conection.setRequestProperty("User-Agent", "USER_AGENT");
            conection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            conection.setRequestProperty("Authorization", "Token " + token);// evince
            conection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conection.setRequestProperty("Accept-Encoding", "identity");
            int responseCode = conection.getResponseCode();

现在我想修改下载过程以使用 android 的 DownloadManager,问题是我如何在 DownloadManager 的请求对象中设置所有这些请求属性,就像上面的代码片段一样。因为如果不设置这些属性,下载将继续失败。

提前谢谢。

经过研究,我终于想出了如何做到这一点。

        DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.addRequestHeader("Authorization", "Token " + token);
        request.addRequestHeader("Accept-Language", "en-US,en;q=0.5");
        request.addRequestHeader("Content-Type", "application/json; charset=UTF-8");
        request.addRequestHeader("Accept-Encoding", "identity");
        request.addRequestHeader("User-Agent", "USER_AGENT");
        File direct = new File(Environment.getExternalStorageDirectory() + "/Abeti");
        if (!direct.exists()) {
            direct.mkdirs();
        }
        request.setDestinationInExternalPublicDir("/Abeti", filenamex);
        request.setTitle(cw.getTitle());

        enqueue = downloadManager.enqueue(request);

用户代理也有同样的问题。这对我来说很有效:

DownloadManager dManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl + "?sid=" + sessionId));
request.addRequestHeader("User-Agent", System.getProperty("http.agent") + " myApp_app/" + Utils.appVersionNumber());
dManager.enqueue(request);

相关内容

  • 没有找到相关文章

最新更新