5

I'm trying to write a client for either HTTP Post or HTTP Get using HttpClient. When Googling around I come across these methods that set these authentication within the HttpClient object. One uses NetworkCredential while the other uses AuthenticationHeaderValue

HttpClient sClient;
HttpClientHandler sHandler = new HttpClientHandler();
sHandler.Credentials = new NetworkCredential("UserName", "Password");
sClient = new HttpClient(sHandler);

OR

HttpClient sClient new HttpClient();
sClient.DefaultRequestHeaders.Authorization = 
  new AuthenticationHeaderValue("Basic",Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("UserName:Password")));

Reading on MSDN does not give me a distinct answer about the differences between them. Is this a case where both will do the same thing except how its authentication information is stored? such as AuthenticationHeaderValue puts it in the header while the other doesn't? Is one better than the other in term of my use case or best practices ?

Fylix
  • 2,551
  • 6
  • 45
  • 72
  • 1
    Having the same question. And the first approach worked while the 2nd didn't. Wondering why. Here's the SO link for the [first approach](http://stackoverflow.com/questions/10292730/httpclient-getasync-with-network-credentials). Here's the link to the [second approach](http://stackoverflow.com/a/14628308/695964) – KFL Feb 16 '15 at 23:36
  • Having the same question. And only the second approach works. – SerG Feb 02 '18 at 12:35

1 Answers1

1

The 2nd approach is more flexible in such way that you can specify a type of authentication (e.g., anonymous, basic, window, certificate, etc) to use.

If your first approach doesn't work, try to specify the 3rd param on NetworkCredential, which is the domain name.

frostshoxx
  • 538
  • 1
  • 7
  • 24