AndroidClientHandler sometimes throws NetworkOnMainThreadException. This problem doesn't always occur but I observed it on the Android emulators. I guess it depends on the underlying HttpUrlConnection implementation which probably varies between devices / OS versions?
Anyways, here's the line that can throw the exception (line 254 inside HttpClientHandler.cs):
var statusCode = (HttpStatusCode)httpConnection.ResponseCode;
You need to wrap it in a task to prevent the NetworkOnMainThreadException from being thrown:
var statusCode = await Task.Run(() => (HttpStatusCode)httpConnection.ResponseCode);
I created my own sub-class to workaround this problem:
public class AndroidClientHandler : global::Xamarin.Android.Net.AndroidClientHandler
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
//Wrap it in a task, work around for run on ui thread bug
return await Task.Run(() => base.SendAsync(request, cancellationToken));
PR with the fix created: https://github.com/xamarin/xamarin-android/pull/247
And it's fixed in monodroid/master, commit 2c02bcf1f4e002941c3beca661075da5cc1ac087
Correction, it's xamarin-android/master, commit 2c02bcf1f4e002941c3beca661075da5cc1ac087
Fix included in monodroid/master, commit 3aae2ff34d7ae746d53310fb5bc73d40b2908aaa
Notice (2018-05-21): bugzilla.xamarin.com will be
switching to read-only mode on Thursday, 2018-05-25 22:00 UTC.
Please join us on
Visual Studio Developer Community and
GitHub to continue tracking
issues. Bugzilla will remain available for reference in read-only mode.
We will continue to work on open Bugzilla bugs and copy them to the new
locations as needed for follow-up. The See Also field
on each Bugzilla bug will be updated with a link to its new location
After Bugzilla is read-only, if you have new information to add for a
bug that does not yet have a matching issue on Developer Community or
GitHub, you can create a follow-up issue in the new location. Copy and
paste the title and description from this bug, and then add your new
details. You can get a pre-formatted version of the title and
In special cases you might also want the comments:
Our sincere thanks to everyone who has contributed on this bug tracker
over the years. Thanks also for your understanding as we make these
adjustments and improvements for the future.