我试图将GET方法发送到Web REST api,它需要以这种形式授权:
Authorization: Basic <Base64 value of UTF-8 encoded “username:password”>
这个请求给了我:
Response status code does not indicate success: 401 (Unauthorized).
代码:
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());
}
虽然uAuth
只是Base64
Username:Password
代表:
string uAuth =
Convert.ToBase64String(
Encoding.UTF8.GetBytes("username:password")
);
我做错了吗?
编辑: 也试过:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);
答案 0 :(得分:2)
您可以使用Authorization
上的DefaultRequestHeaders
属性:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);