带有“@”的 HttpClient 访问 url(在符号处)

Posted

技术标签:

【中文标题】带有“@”的 HttpClient 访问 url(在符号处)【英文标题】:HttpClient access url with '@' (at symbol) 【发布时间】: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 .

有人知道怎么做吗?

【问题讨论】:

带有username:password 凭据的URI 需要使用基本身份验证转换为请求:baeldung.com/httpclient-4-basic-authentication 【参考方案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");
    

【讨论】:

以上是关于带有“@”的 HttpClient 访问 url(在符号处)的主要内容,如果未能解决你的问题,请参考以下文章

Httpclient与RestTemplate的比较(比httpClient更优雅的Restful URL访问)

Spring RestTemplate: 比httpClient更优雅的Restful URL访问

使用浏览器访问一个url能正常访问,但是通过java httpclient请求时却总是超时,是怎么回事啊?

是否可以增加 HttpClient 中的最大 URL 长度? (无效的 URI:uri 字符串太长)

HttpClient--使用HttpClient进行Get Post请求访问

Java的HttpClient如何去支持无证书访问https