使用Xamarin Android通过http基本身份验证下载文件

时间:2017-11-01 15:56:44

标签: c# android xamarin android-download-manager http-authentication

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

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

    }

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

1 个答案:

答案 0 :(得分:1)

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

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