简体   繁体   English

HttpClient 无法解析“UTF-8”内容类型

[英]HttpClient can't parse “UTF-8” Content-Type

I am experiencing a known bug in the HttpClient .我在HttpClient中遇到了一个已知错误。 Anytime the server response contains "UTF-8" (including quotes), an exception is triggered:只要服务器响应包含"UTF-8" (包括引号),就会触发异常:

The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set. ---> System.ArgumentException: '"utf-8"' is not a supported encoding name. 

Example code:示例代码:

HttpClient _client = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.facebook.com");
requestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.4044.55 Safari/537.36");

HttpResponseMessage response = _client.SendAsync(requestMessage).GetAwaiter().GetResult();

What is the usual workaroud?通常的解决方法是什么? I am using .NETFramework 4.6.1.我正在使用 .NETFramework 4.6.1。

To workaround the referenced issue:要解决引用的问题:

using (var client = new HttpClient())
{
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, 
        "https://www.facebook.com");
    HttpResponseMessage response = await client.SendAsync(requestMessage);

    byte[] buf = await response.Content.ReadAsByteArrayAsync();
    string content = Encoding.UTF8.GetString(buf);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM