Android Studio WebView -下载扩展名为admin-ajax.php的文件 &g



我一直在学习Android Studio(我不是专家)。然而,我设法从一个网站编码我的WebView应用程序,我不能让它下载文件作为他们的原始文件名…由于某些原因,我得到一个"admin-ajax。php">

这是MainActivity.java上的代码:

mywebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long l) {
//file name
String fileName = URLUtil.guessFileName(url,contentDisposition,getFileType(url));
sFileName = fileName.substring(fileName.lastIndexOf('/')+1);
sURL = url;
sUserAgent = userAgent;
//check android version
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission( MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
==PackageManager.PERMISSION_GRANTED){
downloadFile(fileName,url,userAgent);
}else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
,  1001);
}
}else{
downloadFile(fileName,url,userAgent);
}

}
public void onPageStarted(WebView view,String url, Bitmap favicon){
onPageStarted (view,url, favicon);
}
});
}
@Override
public void onBackPressed() {
if (webView.canGoBack())
webView.goBack();
else
super.onBackPressed();
}
public String getFileType(String url){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(Uri.parse(url)));
}
private void downloadFile(String fileName, String url, String userAgent){
try {
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request (Uri.parse(url));
String cookie  = CookieManager.getInstance().getCookie(url);
request.setTitle(fileName)
.setDescription("is being downloaded")
.addRequestHeader("cookie",cookie)
.addRequestHeader("User - Agent", userAgent)
.setMimeType(getFileType(url))
.setAllowedOverMetered(true)
.setAllowedOverRoaming(true)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
|DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
sURL = "";
sUserAgent = "";
sFileName = "";
Toast.makeText( this, "Download Started", Toast.LENGTH_SHORT).show();
}catch (Exception ignored){
Toast.makeText( this, "error"+ignored, Toast.LENGTH_SHORT).show();
}
}

public void onRequestPermissionResult(int requestCode, @NonNull String [] permissions, int[] grantResults){
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if (requestCode==1001){
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (!sURL.equals("")&&!sFileName.equals("")&&!sUserAgent.equals("")){
downloadFile(sFileName,sURL,sUserAgent);
}
}
}
}

有什么问题吗?

感谢大家的支持

亲切的问候,

使用下面的代码。

i.setDataAndType(uri, "application/pdf");替换为另一种类型的文件扩展名
  1. 文件扩展名不是pdf;和

  2. 你想在下载后打开文件。

    public class WebViewActivity extends AppCompatActivity {
    ...
    private String fileName;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    webView.setDownloadListener(new DownloadListener() {
    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition,
    String mimeType, long contentLength) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    //setup the fileName
    //fileName = URLUtil.guessFileName(url,contentDisposition,mimeType);
    fileName = (contentDisposition.substring(contentDisposition.lastIndexOf("filename*=UTF-8")+17));
    request.setMimeType(mimeType);
    String cookies = CookieManager.getInstance().getCookie(url);
    request.addRequestHeader("cookie",cookies);
    request.addRequestHeader("User-Agent",userAgent);
    request.setDescription("Downloading File");
    request.setTitle(fileName));
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
    fileName);
    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    //Registering receiver in Download Manager
    registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));    
    downloadManager.enqueue(request);
    Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
    }
    });
    ...
    BroadcastReceiver onCompleted = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
    Uri uri = FileProvider.getUriForFile(WebViewActivity.this, "com.example.app"+".provider",file);
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(uri, "application/pdf");
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(i);
    }
    };
    }
    

最新更新