我正在集成一项服务,当我向以下格式的 URL 发出 GET 请求时,该服务会返回一个 key :
https://username:password@service.com/refresh.key
当我在浏览器中访问 URL 时,它会按预期返回新 key ,当我使用 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的Authorization header,你可以试试下面的代码;
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 请求,所以实际上你尝试进行基本身份验证请求。
希望这对你有用
关于c# - 带有 '@'(在符号处)的 HttpClient 访问 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39852498/