gpt4 book ai didi

c# - ContentType 中提供的字符集无效

转载 作者:行者123 更新时间:2023-11-30 23:03:38 32 4
gpt4 key购买 nike

我用 async await 写了一些简单的代码,但是当我尝试运行它时,编译器抛出一个 System.InvalidOperationException

完整的错误信息是:

Unhandled Exception: System.InvalidOperationException: The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.

System.ArgumentException: 'ISO-8859-2' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

代码:

class Program
{
static async Task Main(string[] args) => await asyncDoItAsync();

private static async Task<string> asyncDoItAsync()
{
HttpClient client = new HttpClient();
Task<string> url = client.GetStringAsync("http://google.pl");

while(!url.IsCompleted)
{
WhenWaiting();
}

string url_length = await url;

return url_length;
}

private static void WhenWaiting()
{
Console.WriteLine("Waiting ...");
Thread.Sleep(90);
}
}

最佳答案

GetStringAsync 似乎不支持响应中的 iso-8859,您基本上无能为力。所以你需要从 GetAsync 开始。请务必清除现有 header ,否则它可能仍会失败。以下适用于您提供的网址(尽管我使用的是 ISO-8859-1 而不是 2):

var client = new HttpClient();
client.DefaultRequestHeaders.Clear();
string s = null;
var result = await client.GetAsync("http://google.pl");
using (var sr = new StreamReader(await result.Content.ReadAsStreamAsync(), Encoding.GetEncoding("iso-8859-1")))
{
s = sr.ReadToEnd();
}

关于c# - ContentType 中提供的字符集无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828449/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com