windows phone 8.1/Windows 8.1中http客户端请求操作如何设置超时
How to set time out for http client request operation in windows phone 8.1/Windows 8.1
如何设置超时 属性 到 Windows.Web.Http.HttpClient
操作。我使用的代码示例如下。
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)
{
}
}
使用 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 ...
}
如何设置超时 属性 到 Windows.Web.Http.HttpClient
操作。我使用的代码示例如下。
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)
{
}
}
使用 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 ...
}