Download a file through http basic authentication with Xamarin Android

点点圈 提交于 2019-12-11 16:09:57

问题


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...


回答1:


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

The DownloadCompleteReceiver implementation is:

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


来源:https://stackoverflow.com/questions/47058862/download-a-file-through-http-basic-authentication-with-xamarin-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!