HttpClient.GetAsync with network credentials

Jan K. picture Jan K. · Apr 24, 2012 · Viewed 80.2k times · Source

I'm currently using HttpWebRequest to get a website. I'd like to use the await pattern, which is not given for HttpWebRequests. I found the class HttpClient, which seems to be the new Http worker class. I'm using HttpClient.GetAsync(...) to query my webpage. But I'm missing the option to add ClientCredentials like HttpWebRequest.Credentials. Is there any way to give the HttpClient authentication information?

Answer

dtb picture dtb · Apr 24, 2012

You can pass an instance of the HttpClientHandler Class with the credentials to the HttpClient Constructor:

using (var handler = new HttpClientHandler { Credentials = ... })
using (var client = new HttpClient(handler))
{
    var result = await client.GetAsync(...);
}