Search code examples
androidxamarinxamarin.formsdotnet-httpclient

HttpClient.SendAsync throws ObjectDisposedException on Xamarin.Forms Android but not on UWP


I'm writing a Xamarin.Forms application and I'm trying to do a Post to my webserver with some JSON payload.

This works fine in UWP, but on Android I get the following error:

 System.ObjectDisposedException: Can not access a closed Stream.
  at System.IO.StreamHelpers.ValidateCopyToArgs (System.IO.Stream source, System.IO.Stream destination, System.Int32 bufferSize) [0x0003a] in <19853c43ab794d18ab1a33ecb65b3c4d>:0 
  at System.IO.MemoryStream.CopyToAsync (System.IO.Stream destination, System.Int32 bufferSize, System.Threading.CancellationToken cancellationToken) [0x00000] in <19853c43ab794d18ab1a33ecb65b3c4d>:0 
  at Xamarin.Android.Net.AndroidClientHandler.WriteRequestContentToOutput (System.Net.Http.HttpRequestMessage request, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken) [0x0009a] in <2bd1b8f6e97f44bbb32ce356b78d4ce6>:0 
  at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x002f4] in <2bd1b8f6e97f44bbb32ce356b78d4ce6>:0 
  at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x002cf] in <2bd1b8f6e97f44bbb32ce356b78d4ce6>:0 
  at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in <c85119bf7e3e421490ae6b5487992fff>:0 
  at BB.App.Services.WebserviceHelper.PostToWebservice[T] (System.String url, System.String json) [0x0008d] in C:\_Sources\_BB\BB.App\BB.App\Services\WebserviceHelper.cs:74 

This happens when the following code is executed:

await httpClient.SendAsync(httpRequest);

I found this site where it recommends not putting the creation of the HttpClient in a using statement, I changed this but it didn't fix my problem.

I also found this bug that is supposed to be fixed last year. To be honest this sounds like the most likely candidate but I don't know exactly what to update to get this fix on my pc. I already updated all my xamarin.android.x references in my solution but no luck so far.


Solution

  • So in conclusion what fixed my problem was to

    • going to the properties of the android project,
    • selecting the 'android options' tab,
    • clicking 'advanced'
    • setting the 'httpclient implementation' from 'Android' to 'Managed'