Mono WebClient encoding issue

对着背影说爱祢 提交于 2019-12-05 12:25:44

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 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. You cannot expect an HTTP client to behave correctly when confronted to non-standard site, what you get is unexpected behavior.

Try testing on some web site that respects a minimum of web standards.

Remark: WebClient implements IDisposable, so make sure you wrap it in a using statement.


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/"));
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!