如何查看HttpClient是否连接到离线网站 [英] How to see if HttpClient connects to offline website
问题描述
所以我正在学习本教程:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client 我想知道如何查看我连接的网站是否处于离线状态.
So I'm following this tutorial: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client and I wonder how I can see whether the website where I connect to is offline.
这是我得到的代码
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:54932/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/products").Result;
Console.WriteLine("here");
当 url http://localhost:54932/
在线时,一切正常,并且打印 here
.然而,当网站离线时,here
不会被打印出来.怎么知道ip地址是不是down了?
When the url http://localhost:54932/
is online everything works just fine, and here
is printed. Yet when the website is offline, the here
is not printed. How can I know if the ip adres is down?
推荐答案
您应该设置超时以了解网站是否已启动.
You should set a timeout in order to know if the website is up.
此处的示例 :
// Create an HttpClient and set the timeout for requests
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(10);
// Issue a request
client.GetAsync(_address).ContinueWith(
getTask =>
{
if (getTask.IsCanceled)
{
Console.WriteLine("Request was canceled");
}
else if (getTask.IsFaulted)
{
Console.WriteLine("Request failed: {0}", getTask.Exception);
}
else
{
HttpResponseMessage response = getTask.Result;
Console.WriteLine("Request completed with status code {0}", response.StatusCode);
}
});
这篇关于如何查看HttpClient是否连接到离线网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!