I am facing a issue with downloading files with WebView that can only be downloaded one time by one user, after that url will not return the file. I am using Download Manager to handle the download of files. So, In that case.
WebView makes a request to download file that it triggers setDownloadListener. In that function, we call another API with DownloadManager. That's why I am not able to download the file.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity activity = this;
WebView webView = activity.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.setWebContentsDebuggingEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(false);
webView.getSettings().setAllowFileAccessFromFileURLs(false);
webView.setWebViewClient(new WebViewClient(){});
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
handleDownload(url,userAgent,contentDisposition,mimetype);
}
});
webView.loadUrl("http://192.168.1.40:8080");
}
public void handleDownload(String url, String userAgent, String contentDisposition, String mimetype){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("Cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
String fileName = (new Date().getTime()) + URLUtil.guessFileName(url, contentDisposition, mimetype);
request.setDestinationInExternalFilesDir(this.getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
final DownloadManager dm = (DownloadManager) this.getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
}