您可以使用 CookieManager 检索 cookie,如下所示(我使用 webview):
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String cookieString = CookieManager.getInstance().getCookie(url);
}
});
//Enable Javascript
webView.getSettings().setJavaScriptEnabled(true);
//Clear All and load url
webView.loadUrl(URL_TO_SERVE);
然后将其传递给 DownloadManager:
//Create a DownloadManager.Request with all the information necessary to start the download
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
.setTitle("File")// Title of the Download Notification
.setDescription("Downloading")// Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
.setDestinationUri(Uri.fromFile(file))// Uri of the destination file
.setAllowedOverMetered(true)// Set if download is allowed on Mobile network
.setAllowedOverRoaming(true);
request.addRequestHeader("cookie", cookieString);
/*request.addRequestHeader("User-Agent", cookieString);*/
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.