如何超时网络调用以检索JSON Feed?

时间:2016-06-30 06:47:45

标签: json httpclient

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

1 个答案:

答案 0 :(得分:0)

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);
}
相关问题