c# - 带有 '@'(在符号处)的 HttpClient 访问 url

标签 c# url dotnet-httpclient .net-4.5.2

我正在集成一项服务,当我向以下格式的 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/

相关文章:

c# - HttpClient .Result 在使用 [WebMethod] 属性时挂起

c# - 如何将文件作为 MultipartFormDataContent 从表单传递到 HttpClient.PostAsync

c# - 本地化/国际化工具

url - 从URL gradle-wrapper.properties文件?

c# - 调用异步委托(delegate)时防止 Lazy<T> 缓存异常

java - 如何判断我的网站被访问的IP地址?

iphone - 获取ID3标签而不下载iPhone应用程序中的整个文件?

c# - 为什么服务器可能收不到附加到使用 HttpClient 的请求的证书?

c# - 解压缩 PVRTC

c# - 默认后不能出现linq过滤器?