Alex Bakanov Alex Bakanov - 1 year ago 186
C# Question

Xamarin HttpClient works weird

I using HttpClient to send post request on local server (powered on LAMP or MAMP, tried both) but can't get answer, always getting "Task cancelled exception" with following code

using (HttpClient client = new HttpClient())
client.Timeout = new TimeSpan(0, 0, 10);
var sendContent = new StringContent(serialized);

using (HttpResponseMessage response = await client.PostAsync(url.ToString(), sendContent))
if (response.StatusCode != HttpStatusCode.OK)
return MakeError("Bad status: " + response.StatusCode.ToString());

using (HttpContent content = response.Content)
string str = await content.ReadAsStringAsync();
if (str == null)
return MakeError("Got null answer");

App.Log("Response: " + str);
return str;
catch (Exception e)
App.Log("There is something bad with request: " + serialized + " the error was " + e.Message + " url = " + url.ToString());

return MakeError("Timed out");

the url is right, if I trying to execute this code on C# Console Application I can get answer (but not with Xamarin, both Android and iOS, on device and emulators).

I also tried to sniff HTTP packets, and I saw that answer was sent by my local server, but Xamarin didn't handled this right way. BUT, if replace url with domain (for example I can get answer.

Following HTTP answer headers:

  1. Connection →close (keep-alive doesn't works too)

  2. Content-Length →951

  3. Content-Type →application/json

  4. Date →Thu, 16 Jun 2016 18:11:40 GMT

  5. Server →Apache

  6. X-Powered-By →PHP/5.5.14

Any suggestions?

Answer Source

One possible issue is your 8 second timeout.

From HttpClient documentation:

The default value is 100,000 milliseconds (100 seconds).

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

So 15 seconds at least are needed for the DNS query if that is taking place in your call. Remove the timeout and see if the issue is still there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download