我需要在Wp8.1应用程序中为所有Http Web请求设置10秒的超时。我在Timeout
课程中找不到ContinueTimeout
而不是HttpWebRequest
属性。
快速搜索提供了一些替代方案。使用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
}
}
答案 0 :(得分:0)
您可以使用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)
{
}
答案 1 :(得分:0)
您可以创建一个扩展方法,而不是接受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);
}
}
}
}
顺便说一下,你有没有理由不使用WP 8.1中的GetResponseAsync
?请参阅内联代码注释。