Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set time out for http client request operation in windows phone 8.1/Windows 8.1

How to set Timeout property to Windows.Web.Http.HttpClient operation. The code sample I used is below.

public HttpClient httpClient;
public CancellationTokenSource cts;

public void SendRequest(addressUri,postrequestbody)
{
    HttpHelper.CreateHttpClient(ref httpClient);
    cts = new CancellationTokenSource();
    HttpRequestMessage msg = 
        new HttpRequestMessage(new HttpMethod("POST"), 
                               new Uri(addressUri));
    msg.Content = new HttpStringContent(postrequestbody);
    msg.Content.Headers.ContentType = 
        new HttpMediaTypeHeaderValue("application/json");
    HttpResponseMessage response = 
        await httpClient.SendRequestAsync(msg).AsTask();

    if (response.StatusCode == HttpStatusCode.Ok)
    {
    }
}
like image 940
asitis Avatar asked Jan 21 '15 06:01

asitis


People also ask

What is Httpclient default timeout?

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

What is HttpRequestMessage C#?

HttpRequestMessage(HttpMethod, String) Initializes a new instance of the HttpRequestMessage class with an HTTP method and a request Uri. HttpRequestMessage(HttpMethod, Uri) Initializes a new instance of the HttpRequestMessage class with an HTTP method and a request Uri.


1 Answers

Use a CancellationToken:

try 
{
    CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await
        client.SendRequestAsync(request).AsTask(cts.Token);
}
catch (TaskCanceledException ex)
{
    // Catch operation aborted ...
}
like image 53
kiewic Avatar answered Oct 20 '22 06:10

kiewic