使用HttpClient时出现未经授权的错误 [英] unauthorized error when using HttpClient
本文介绍了使用HttpClient时出现未经授权的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace ConsoleProgram
{
public class Class1
{
private const string URL = "https://sun.domain.com/v1/service/token";
static void Main(string[] args)
{
var handler = new HttpClientHandler();
handler.Credentials = new System.Net.NetworkCredential("admin@client", "admin");
HttpClient client = new HttpClient(handler);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "admin", "admin"))));
// client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(URL).Result; // Blocking call!
String res = response.ToString();
Console.WriteLine(res);
}
}
}
即使我传递了正确的凭据,也遇到了未经授权的错误.有什么想法吗?
I am getting unauthorized error even though I am passing the correct credentials. Any ideas?
我尝试了在StackOverflow上发布的几乎所有答案.
I tried almost all the answers posted on StackOverflow.
推荐答案
对于基本身份验证,您需要在名为"Basic"的授权标头中发送凭据,并以base64编码的"username:password"作为值.这应该可以完成工作:
For Basic Authentication, you need to send the credentials in an authorization header called "Basic" with base64-encoded "username:password" as the value. This should get the job done:
var headerVal = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin@client:admin"));
var header = new AuthenticationHeaderValue("Basic", headerVal);
client.DefaultRequestHeaders.Authorization = header;
这篇关于使用HttpClient时出现未经授权的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文