我需要为Wp8.1应用程序中的所有Http web请求设置10秒的超时。我没有在HttpWebRequest
类中找到Timeout
而不是ContinueTimeout
属性。
快速搜索给了我们几个选择。使用CancellationToken是一个而另一个是使用Task。是否有人给我指点一下如何修改我当前的代码。
这是我如何创建一个请求
string uri = MyClass.HTTP_URI + "user/server-timestamps";
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = MyClass.HTTP_GET;
request.Accept = "application/json";
request.Headers[HTTP_AUTHENTICATION_TOKEN] = "token"
request.Headers[API_KEY] = API_KEY_VALUE;
这是我发送请求的方式
try
{
WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
HttpWebResponse response = (HttpWebResponse)responseObject;
statusCode = (int)response.StatusCode;
if (statusCode == 200)
{
var responseStream = responseObject.GetResponseStream();
var sr = new StreamReader(responseStream);
received = await sr.ReadToEndAsync();
//Do stuff
}
}
可以使用HttpClient类和CancellationTokenSource。修改一下。
try
{
CancellationTokenSource cts = new CancellationTokenSource(2000);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue(""));
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), new Uri("Url"));
HttpResponseMessage response = await client.SendRequestAsync(msg).AsTask(cts.Token);
}
catch(TaskCanceledException ex)
{
}
您可以创建一个接受CancellationToken
的扩展方法,并像这样使用它:
var request = (HttpWebRequest)WebRequest.Create(uri);
// ...
try
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
await request.GetResponseAsyncCancelable(cts.Token);
}
}
catch (OperationCanceledException)
{
// handle cancellation, if desired
}
// ...
public static class HttpWebRequestExt
{
public static async Task<HttpWebResponse> GetResponseAsyncCancelable(
this HttpWebRequest @this,
CancellationToken token)
{
using (token.Register(() => request.Abort(), useSynchronizationContext: false))
{
try
{
// BTW: any reason why not use request.GetResponseAsync,
// rather than FromAsync? It's there in WP 8.1:
// var response = await request.GetResponseAsync();
var response = (HttpWebResponse)await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
token.ThrowIfCancellationRequested();
return response;
}
catch (WebException ex)
{
// WebException caused by cancellation?
if (!token.IsCancellationRequested)
throw; // no, just re-throw
// yes, wrap it with OperationCanceledException
throw new OperationCanceledException(ex.Message, ex, token);
}
}
}
}
顺便说一句,有什么原因你没有使用GetResponseAsync
,这是在WP 8.1?