简体   繁体   English

将WP8.1中的HttpWebRequest设置为10秒的超时

[英]Set Timeout of 10 seconds to HttpWebRequest in WP8.1

I need to set a timeout of 10 seconds to all the Http web request in Wp8.1 app. 我需要为Wp8.1应用程序中的所有Http Web请求设置10秒的超时。 I dont find a Timeout instead a ContinueTimeout property in the HttpWebRequest class. 我没有在HttpWebRequest类中找到Timeout而是ContinueTimeout属性。

A Quick search gave be few alternatives. 快速搜索给出了几种选择。 Using a CancellationToken being one and the other one is using Task. 使用CancellationToken作为一个,另一个使用Task。 Will some one give me pointers as to how to modify my current code. 请问有人给我有关如何修改当前代码的指示。

This is how I'm creating a request 这就是我创建请求的方式

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;

This is how I'm sending the request 这就是我发送请求的方式

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

You can use HttpClient class and CancellationTokenSource. 您可以使用HttpClient类和CancellationTokenSource。 Just modify it. 只需对其进行修改。

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

}

You can create an extension method than accepts CancellationToken and use it like this: 您可以创建一个扩展方法,而不是接受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);
            }
        }
    }
}

BTW, is there any reason you're not using GetResponseAsync , which is there in WP 8.1? 顺便说一句,是否有任何原因不使用WP 8.1中的GetResponseAsync See the code comments inline. 请参见内联代码注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM