我正在集成一个服务,当我发出GET请求时,该服务会返回一个以下格式的URL:
https://username:password@service.com/refresh.key
当我在浏览器中访问URL时,它会按预期返回新密钥,当我使用HttpClient
执行GET请求时,我得到401。
HttpClient _client = new HttpClient();
var response = await _client.GetAsync(@"https://username:password@service.com/refresh.key"); // Returns a 401
我认为它与网址中的'@'
有关,但我不确定如何修复它,我尝试用'%40'
替换它,但是当我这样做时,我得到了UriFormatException
。
有谁知道怎么做?
答案 0 :(得分:3)
你应该修改HttpClient的授权标题,你能尝试下面的代码吗?
HttpClient _client = new HttpClient();
byte[] usernamePasswordBytes = Encoding.ASCII.GetBytes("user:pass");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(usernamePasswordBytes));
var response = await _client.GetAsync(@"https://service.com/refresh.key");
PS:此类用户名:pass@domain.com请求是BasicAuthentication请求,因此实际上您尝试进行基本身份验证请求。
希望这适合你
答案 1 :(得分:2)
您不需要在网址中提供凭据。相反,你可以这样做:
using (var handler = new HttpClientHandler {Credentials = new NetworkCredential("username", "password")}) {
using (HttpClient _client = new HttpClient(handler)) {
var response = await _client.GetAsync(@"https://service.com/refresh.key");
}
}