我很难让android webview从我的服务器应用程序下载文本文件。看起来它可能与传输协议或会话变量有关。使用Web浏览器应用程序时文件下载正常,但在我的自定义Webview代码中不起作用。在我的自定义代码中,下载了一个文件,但它不是请求的文本文件。相反,它是登录屏幕的HTML代码。服务器导出器检查用户是否在导出之前登录并重定向到登录屏幕。
以下是webview下载代码:
mWebView.setWebViewClient(new myWebClient());
mWebView.setDownloadListener(this);
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
// Notify client once download is completed!
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
final String exportFileName = URLUtil.guessFileName(
url, contentDisposition, mimetype);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, exportFileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
// This is important!
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); // CATEGORY.OPENABLE
intent.setType("*/*");// any application,any extension
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}
在服务器端,这些是生成文本文件之前使用的标头:
header("Content-Type: text/plain" );
header("Content-Disposition: attachment; filename=".$this->filename);
答案 0 :(得分:1)
向新的DownloadManager.Request添加cookie解决了这个问题。
String cookie = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("Cookie", cookie);