如何使用HttpClient的凭据,在C#中? [英] How to use credentials in HttpClient in c#?

查看:676
本文介绍了如何使用HttpClient的凭据,在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HttpClient的类来获得美味的API时面临的一些问题。我有以下的code:

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

在运行code上面我得到以下几点:响应状态code并不表示成功:401

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?

在此先感谢

祺!

推荐答案

我有完全相同的问题我自己。看来的HttpClient 只是无视中设置的凭据 HttpClientHandler

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

以下仍应工作:

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

没有必要的处理程序。

来源:<一个href=\"http://www.snip2$c$c.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us\">http://www.snip2$c$c.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us

这篇关于如何使用HttpClient的凭据,在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆