简体   繁体   中英

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)
    {
    }
}

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 ...
}

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