[英]c# How do I add 'Authorization: Basic' to my HttpClient header?
I'm trying to send GET method to a web REST api and it requires authorization in this form: 我正在尝试将GET方法发送到Web REST api,并且需要这种形式的授权:
Authorization: Basic <Base64 value of UTF-8 encoded “username:password”>
This request gives me: 这个要求给我:
Response status code does not indicate success: 401 (Unauthorized).
Code: 码:
try
{
var client = new HttpClient();
client.BaseAddress = bUrl; // https url
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-type", "application/xml");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + uAuth);
HttpResponseMessage XmlResponse = await client.GetAsync(url);
XmlResponse.EnsureSuccessStatusCode();
string xml = await XmlResponse.Content.ReadAsStringAsync();
Debug.WriteLine(xml);
}
catch (HttpRequestException hre) {
Debug.WriteLine(hre.ToString());
} catch (Exception ex) {
Debug.WriteLine(ex.ToString());
}
While uAuth
is just a Base64
Username:Password
representation: 尽管uAuth
只是Base64
Username:Password
表示形式:
string uAuth =
Convert.ToBase64String(
Encoding.UTF8.GetBytes("username:password")
);
Am I doing something wrong? 难道我做错了什么?
edit: Tried also with: 编辑:也尝试过:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);
您可以使用DefaultRequestHeaders
上的Authorization
属性:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.