Skip to content Skip to sidebar Skip to footer

Download A File Through Http Basic Authentication With Xamarin Android

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 av

Solution 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:

publicclassDownloadCompleteReceiver : BroadcastReceiver
{
    long id;
    EventHandler handler;
    publicDownloadCompleteReceiver(long id, EventHandler handler){
        this.id = id;
        this.handler = handler;
    }
    publicoverridevoidOnReceive(Context context, Intent intent){
        if (intent.Action == DownloadManager.ActionDownloadComplete &&
             id == intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0))
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
}

Post a Comment for "Download A File Through Http Basic Authentication With Xamarin Android"