简体   繁体   English

Mono WebClient编码问题

[英]Mono WebClient encoding issue

I'm trying to port a .NET application from Windows to Mono, but certain code that was working on Windows is no longer working ( as expected ) on mono : 我正在尝试将.NET应用程序从Windows移植到Mono,但是在Windows上运行的某些代码在mono上不再起作用( 按预期 ):

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

it seems to detect correctly the encoding as UTF-8 (and manually setting the encoding to UTF-8 or ASCII don't work either) there are still '?' 似乎可以正确检测到UTF-8编码(并且将编码手动设置为UTF-8或ASCII也不起作用) ,仍然存在“?” characters 人物

You are writing to the console. 您正在写控制台。 Maybe your console is not configured properly to show certain characters. 也许您的控制台配置不正确,无法显示某些字符。 Make sure by debugging and storing the result into an intermediary variable. 通过调试并将结果存储到中间变量中来确保。

Also the site you gave as example is completely messed up. 您作为示例给出的网站也完全混乱了。 The web server sends Content-Type: text/html; charset=iso-8859-1 Web服务器发送Content-Type: text/html; charset=iso-8859-1 Content-Type: text/html; charset=iso-8859-1 HTTP header and in the resulting HTML you see <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> which of course is completely incoherent. Content-Type: text/html; charset=iso-8859-1 HTTP标头,在生成的HTML中,您会看到<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ,这当然是完全不连贯的。 You cannot expect an HTTP client to behave correctly when confronted to non-standard site, what you get is unexpected behavior. 当遇到非标准站点时,您不能指望HTTP客户端能够正确运行,而您得到的是意外行为。

Try testing on some web site that respects a minimum of web standards. 尝试在某些遵循最低Web标准的网站上进行测试。

Remark: WebClient implements IDisposable , so make sure you wrap it in a using statement. 备注: WebClient实现IDisposable ,因此请确保将其包装在using语句中。


UPDATE: 更新:

To make it work with this particular site you may try downloading the response manually and specifying the correct encoding: 要使其与该特定站点一起使用,您可以尝试手动下载响应并指定正确的编码:

// 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);
    }
}
 using (var client = new WebClient())
        {
            client.Encoding = Encoding.UTF8;
           Console.WriteLine (client.DownloadString("http://www.maxima.fm/51Chart/"));
        }

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

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