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)
{
}
}
The default value is 100,000 milliseconds (100 seconds).
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.
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 ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With