Reputation: 1407
I'm trying to send GET method to a web REST api and it requires authorization in this form:
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:
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);
Upvotes: 5
Views: 7329
Reputation: 67336
There should be an Authorization
property on DefaultRequestHeaders
that you can use:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);
Upvotes: 4