Home > front end >  Convert WebRequest into httpclient in C#
Convert WebRequest into httpclient in C#

Time:12-22

Got this code

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "HEAD";
request.Timeout = 3000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;

how to convert this code into httpclient since WebRequest.Create(host) is obsolete, this code is called on the first time app open, located in formload to check internet connection active and host/domain I check is up

Thank you

CodePudding user response:

You can call it this way, just notice it's async.

using (HttpClient client = new HttpClient())
{
    client.Timeout = TimeSpan.FromMilliseconds(3000);
    HttpResponseMessage response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, host));
    return response.IsSuccessStatusCode;
}
  •  Tags:  
  • c#
  • Related