简体   繁体   中英

Xamarin HttpClient: TaskCancelledException

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

try
{
    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 http://stackoverflow.com ) 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?

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.

I had the same issue. i have added following line, i was able to get the response.

httpClient.DefaultRequestHeaders.ConnectionClose = true;

just try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM