gpt4 book ai didi

c# - Mono WebClient 编码问题

转载 作者:行者123 更新时间:2023-11-30 12:36:08 25 4
gpt4 key购买 nike

我正在尝试将一个 .NET 应用程序从 Windows 移植到 Mono,但是在 Windows 上工作的某些代码不再工作(如预期的那样)强>单声道:

WebClient client = new WebClient ();
Console.WriteLine (client.DownloadString("http://www.maxima.fm/51Chart/"));

它似乎正确检测到编码为 UTF-8(手动将编码设置为 UTF-8 或 ASCII 也不起作用)仍然有“?”字符

最佳答案

您正在写入控制台。也许您的控制台配置不正确,无法显示某些字符。通过调试并将结果存储到中间变量中来确保。

此外,您作为示例提供的网站也完全搞砸了。 Web 服务器发送 Content-Type: text/html; charset=iso-8859-1 HTTP header 和生成的 HTML 中您会看到 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />这当然是完全不连贯的。您不能指望 HTTP 客户端在遇到非标准站点时能够正确运行,您得到的是意想不到的行为。

尝试在一些遵守最低网络标准的网站上进行测试。

备注:WebClient工具 IDisposable ,因此请确保将其包装在 using 中声明。


更新:

要使其与该特定站点一起使用,您可以尝试手动下载响应并指定正确编码:

// You may try different encodings here (for me it worked with iso-8859-1)
var encoding = Encoding.GetEncoding("iso-8859-1");
using (var client = new WebClient())
{
using (var stream = client.OpenRead("http://www.maxima.fm/51Chart/"))
using (var reader = new StreamReader(stream, encoding))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}
}

关于c# - Mono WebClient 编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3826193/

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