使用'@'(符号)
本文关键字:符号 使用 | 更新日期: 2023-09-27 18:11:38
我正在集成一个服务,当我向以下格式的URL发送GET请求时,该服务返回一个键:
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
我认为它与URL中的'@'
有关,但我不确定如何修复它,我尝试用'%40'
替换它,但当我这样做时,我得到了UriFormatException
。
有人知道怎么做吗?
您应该修改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:这样的username:pass@domain.com请求是BasicAuthentication请求,所以实际上你尝试进行基本身份验证请求。
希望这对你有用
您不需要在url中提供凭证。你可以这样做:
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");
}
}