Search code examples
c#httpclienthttpwebrequest

Convert WebRequest into httpclient in C#


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


Solution

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