c# - HttpRequestHeader 内容编码问题

标签 c# encoding webclient

我正在使用下面的代码片段将 HTTP 响应下载到本地文件。 有时我在 url 中的内容是多语言的(中文、日文、泰文等)。 我正在使用 ContentEncoding header 来指定我的内容采用 UTF-8 编码,但这对以 ASCII 生成的本地输出文件没有影响。因此,多语言数据已损坏。有帮助吗?

using (var webClient = new WebClient())
        {
            webClient.Credentials = CredentialCache.DefaultCredentials;
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0");
            webClient.Headers.Add(HttpRequestHeader.ContentEncoding, "utf-8");

            webClient.DownloadFile(url, @"c:\temp\tempfile.htm");
        }

最佳答案

ContentEncoding header 不用于指定字符集。客户端使用它来说明它支持哪种编码(压缩)。

客户端无法告诉服务器发送什么字符集。服务器发送其数据和一些 header 字段,说明正在使用的字符集。通常它位于 ContentType header 中,看起来像:text/html; charset=UTF-8.

当您使用 WebClient 时,您希望将 Encoding 属性设置为备用,这样如果服务器无法识别字符集,您的默认值将使用。例如:

WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string s = client.DownloadString(DownloadUrl);

参见 http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=800了解更多信息。

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

相关文章:

java - 从 http GET 响应获取图像作为 base64 字符串

c# - WebClient - 获取有关错误状态代码的响应正文

c# - Moonlight、WebClient 和 "Exception has been thrown by the target of an invocation"

c# - 使用 C# 解析 robots.txt 文件中的各个行

c# - 需要在没有导航属性的情况下在 Entity Framework 中做等效的 .Any

c# - C#条件对象声明

c# - 我的 asp.net mvc web 应用程序中的 OutputCache 设置。防止缓存的多种语法

c# - 使用空日期时间对 DataGridView 进行排序

php - 阿拉伯语编码的数据库问题

C++ 标准 :string comparation codification problems