Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

windows phone 7 - How to use credentials in HttpClient in c#?

I am facing some problems when using the HttpClient class to access to a 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 running the code above I am getting the following: Response status code does not indicate success: 401 (Unauthorized).

So, how could I get this work? Is it possible?

Thanks in advance

Regards!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had the exact same problem myself. It seems the HttpClient just disregards the credentials set in the HttpClientHandler.

The following shall work however:

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

No need for the handler.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...