使用 Xamarin Android 通过 http 基本身份验证下载文件 [英] Download a file through http basic authentication with Xamarin Android

查看:47
本文介绍了使用 Xamarin Android 通过 http 基本身份验证下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Xamarin Android 应用程序中使用 WebView 访问企业 Intranet.我可以在 Intranet 中正确查看和导航,但无法下载那里可用的文件.这是我的代码:

I am accessing to an Enterprise Intranet using a WebView, in a Xamarin Android app. I can see and navigate correctly through the intranet but I am not able to download the files available there. This is my code :

private void MWebview_Download(object sender, DownloadEventArgs e)
    {
        var url = e.Url;
       // var s = url.Replace(" ", "%20");
        DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
        string credentials = "cristina.casas:Tst.30"; //just for try
        // pasar las credenciales a base64
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(credentials);
        var encodedCredentials = System.Convert.ToBase64String(plainTextBytes);

        request.AddRequestHeader("Authorization", "Basic " + encodedCredentials);
        request.SetTitle("descarga.pdf");
        request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
        request.AllowScanningByMediaScanner();
        request.SetMimeType("application/pdf");
        request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, "descarga.pdf");         
        DownloadManager dm = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService);
        dm.Enqueue(request);
        Toast.MakeText(Application.Context, "Downloading File", ToastLength.Long).Show();//To notify the Client that the file is being downloaded

    }

它不起作用.我收到错误下载失败".我在这一点上被困了好几天......

It doesn't work. I get the error "download failed". I am stucked at this point for days...

推荐答案

您的代码看起来正确.尝试以下操作,因为它可以作为使用 HttpWatch 网站的基本身份验证测试.如果它适合您,请替换您的 Intranet 的 uri、用户和密码.

Your code looks correct. Try the following as this works as a basic authentication test using HttpWatch's website. If it works for you, substitute your intranet's uri, user and password.

DownloadCompleteReceiver receiver;
var user = "httpwatch";
var password = new Random().Next(int.MinValue, int.MaxValue).ToString();
var uriString = "https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx?0.05205263447822417";

using (var uri = Android.Net.Uri.Parse(uriString))
using (var request = new DownloadManager.Request(uri))
{
    var basicAuthentication = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}"));
    request.AddRequestHeader("Authorization", $"Basic {basicAuthentication}");
    request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
    request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, "someImage.gif");
    using (var downloadManager = (DownloadManager)GetSystemService(DownloadService))
    {
        var id = downloadManager.Enqueue(request);
        receiver = new DownloadCompleteReceiver(id, (sender, e) =>
        {
            Toast.MakeText(Application.Context, $"Download Complete {id}", ToastLength.Long).Show();
            if (sender is DownloadCompleteReceiver rec)
            {
                UnregisterReceiver(rec);
                rec.Dispose();
            }
        });
        RegisterReceiver(receiver, new IntentFilter(DownloadManager.ActionDownloadComplete));
        Toast.MakeText(Application.Context, $"Downloading File: {id}", ToastLength.Short).Show();
    }
}

DownloadCompleteReceiver 实现是:

public class DownloadCompleteReceiver : BroadcastReceiver
{
    long id;
    EventHandler handler;
    public DownloadCompleteReceiver(long id, EventHandler handler)
    {
        this.id = id;
        this.handler = handler;
    }
    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action == DownloadManager.ActionDownloadComplete &&
             id == intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0))
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
}

这篇关于使用 Xamarin Android 通过 http 基本身份验证下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆