【问题标题】:HttpClient access url with '@' (at symbol)带有“@”的 HttpClient 访问 url(在符号处)
【发布时间】:2016-10-04 12:34:59
【问题描述】:

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

有人知道怎么做吗?

【问题讨论】:

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


【解决方案1】:

你应该修改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 请求,所以实际上你尝试发出基本身份验证请求。

希望这对你有用

【讨论】:

    【解决方案2】:

    您无需在 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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2013-08-21
      • 2014-10-02
      • 1970-01-01
      • 2011-02-03
      相关资源
      最近更新 更多