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

Posted

技术标签:

【中文标题】Android Studio WebView - 下载扩展名为 admin-ajax.php 的文件【英文标题】:Android Studio WebView - Downloading files with admin-ajax.php extension 【发布时间】:2021-11-15 05:46:59 【问题描述】:

我一直在学习 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);
            
        
    

可能是什么问题?

感谢大家的支持。

亲切的问候,

【问题讨论】:

【参考方案1】:

使用下面的代码。将i.setDataAndType(uri, "application/pdf");替换为另一种类型的文件扩展名,如果:

    文件扩展名不是pdf;和

    你想在下载后打开文件。

    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);
         
     ;
    
    

【讨论】:

谢谢!但它还没有工作..我只是用新代码添加了另一个评论,所以你可以帮助我.. 我认为这与网站上的安全功能有关。该代码运行良好,但在 Google Drive 文件和我的网络上也存在问题 :( 网址是什么? 对不起Gedanggoreng。该代码实际上适用于其他网站......但显然问题出在我的网站上,我不知道为什么。这是 wordpress 插件开发人员告诉我的:“插件的下载是通过 WordPress /wp-admin/admin-ajax.php 的公共管理端点处理的。似乎 webview 没有收到以某种方式设置的文件名框架,以便它使用该脚本名称来代替?”这对你有意义吗? 能否告知网站网址以便我查看?

以上是关于Android Studio WebView - 下载扩展名为 admin-ajax.php 的文件的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio在WebView中编译Web应用

简单的 webview 示例代码 Android studio

Android Studio - 如何在 webview Lollipop 中上传文件 (Android 5.0)

Webview 在 Fragment Android Studio 中不起作用

使用 Kotlin 的 Android Studio WebView“期望成员声明”

Android Studio 中的 Webview 确实显示了导航菜单和背景徽标