如何在 c# 中的 HttpClient 中使用凭据? [英] How to use credentials in HttpClient in c#?
问题描述
我在使用 HttpClient 类访问 Delicious API 时遇到了一些问题.我有以下代码:
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);
}
运行上面的代码时,我得到以下信息:响应状态代码不表示成功: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);
}
不需要处理程序.
来源:http://www.snip2code.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us
这篇关于如何在 c# 中的 HttpClient 中使用凭据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!