【问题标题】:How can I timeout a web-call to retrieve a JSON feed?如何使网络调用超时以检索 JSON 提要?
【发布时间】:2016-06-30 06:47:44
【问题描述】:

我正在使用 HttpClient 进行调用以检索 JSON 提要。我想为这个电话设置一个超时时间,以防它需要太长时间。我该怎么做?

【问题讨论】:

  • 据我了解,您想设置 Web 服务调用的超时时间?
  • 你什么时候在谈论响应 aur 请求?

标签: json httpclient


【解决方案1】:

HttpClient 有一个Timeout 属性。将其设置为您想要的超时并处理TimeoutException 以在超时时执行特定操作。

HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(5);
HttpResponseMessage response = null;
try
{
    response = await client.GetAsync(url);
}
catch (TimeoutException)
{
    // handle the timeout, e.g. return false
    return false;
}
catch (Exception ex)
{
    // handle the other errors, e.g. throw it
    throw (ex);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多