单WebClient的编码问题 [英] Mono WebClient encoding issue

查看:191
本文介绍了单WebClient的编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想端口的 .NET 的从Windows到单声道,但某些code表示正在研究Windows应用程序不再工作(如预期的)在

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:

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

它似乎正确地检测编码为UTF-8(手动设置编码设置为UTF-8或ASCII不工作要么)还有?字符

推荐答案

您正在编写到控制台。也许您的控制台未正确配置为显示某些字符。确保通过调试和结果存到中介变量。

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.

另外你给的例子是完全搞砸了该网站。 Web服务器发送的Content-Type:text / html的;字符集= ISO-8859-1 HTTP头,并在你看到生成的HTML < META HTTP-当量=Content-Type的CONTENT =text / html的;字符集= UTF-8/> 这当然是完全不相干。你不能指望一个HTTP客户端时遇到非标准场地正确的行为,你得到的是意外的行为。

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.

尝试在一些网站,尊重最小的Web标准测试。

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

注: WebClient的工具的 IDisposable的,所以一定要确保你在的使用声明。

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

更新:

要使其与您可以尝试手动下载的响应,并指定这个特定的网站工作的正确的编码方式:

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);
    }
}

这篇关于单WebClient的编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆