How to use credentials in HttpClient in C #?

I am encountering some problems when using the HttpClient class to access the Delicious API. I have the following code:

try { const string uriSources = "https://api.del.icio.us/v1/tags/bundles/all?private={myKey}"; using (var handler = new HttpClientHandler { Credentials = new NetworkCredential("MyUSER", "MyPASS") }) { using (var client = new HttpClient(handler)) { var result = await client.GetStringAsync(uriSources); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR...", MessageBoxButton.OK); } 

When I run the code above, I get the following: The response status code does not indicate success: 401 (Unauthorized).

So how could I get this job? Is it possible?

Thank you in advance

Hello!

+22
c # windows-phone-7 windows-phone-8
Aug 28 '13 at 2:36 on
source share
3 answers

I had the same problem. It seems that HttpClient simply ignores the credentials set in the HttpClientHandler .

Next, the following will work:

 using System.Net.Http.Headers; // For AuthenticationHeaderValue const string uri = "https://example.com/path?params=1"; using (var client = new HttpClient()) { var byteArray = Encoding.ASCII.GetBytes("MyUSER:MyPASS"); var header = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(byteArray)); client.DefaultRequestHeaders.Authorization = header; var result = await client.GetStringAsync(uri); } 

There is no need for a handler.

Source: http://www.snip2code.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us

+29
May 28 '14 at 2:37
source

This is an old post, but I was thinking of adding my answer for someone facing a similar problem and looking at the answers ...

I ran into a similar problem. In my case, the work on setting the Domain property for NetworkCredentials worked. You can try installing Domain.

+1
Oct 05 '15 at 12:08
source

The code you show works for me against an authenticated resource. I suspect Delicious is doing something weird.

Given that you are on a Windows Phone, it hurts to debug Fiddler, so I suggest getting Runscope . Install this message handler that will redirect your request through the RunScope debugger. Once you do this, I suggest you look at the www-authenticate header and check what that means.

If all else fails, you can always directly configure the authentication header using basic credentials. You do not need to use the Credentials class.

0
Aug 31 '13 at 16:07
source



All Articles