Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient.GetAsync with network credentials

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?

like image 674
Jan K. Avatar asked Apr 24 '12 06:04

Jan K.


People also ask

What is HttpClientHandler C#?

The HttpClient class uses a message handler to process the requests on the client side. The default handler provided by the dot net framework is HttpClientHandler. This HTTP Client Message Handler sends the request over the network and also gets the response from the server.


2 Answers

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(...); } 
like image 163
dtb Avatar answered Sep 23 '22 02:09

dtb


You shouldn't dispose of the HttpClient every time, but use it (or a small pool of clients) for a longer period (lifetime of application. You also don't need the handler for it, but instead you can change the default headers.

After creating the client, you can set its Default Request Headers for Authentication. Here is an example for Basic authentication:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "username:password".ToBase64()); 

ToBase64() represents a helper function that transforms the string to a base64 encoding.

like image 32
JSilvanus Avatar answered Sep 23 '22 02:09

JSilvanus