HttpWebRequest 响应内容的编码问题

发布于 2024-11-08 22:18:15 字数 1026 浏览 1 评论 0原文

我正在使用 HttpWebRequest 使用以下代码读取网页:

 var pageurl = new Uri(url, UriKind.Absolute);

        var request = (HttpWebRequest)WebRequest.Create(pageurl);
        request.Method = "GET";
        request.AutomaticDecompression = DecompressionMethods.GZip;
        request.KeepAlive = false;
        request.ConnectionGroupName = Guid.NewGuid().ToString();
        request.ServicePoint.Expect100Continue = false;
        request.Pipelined = false;
        request.MaximumResponseHeadersLength = 4;

        if (ignoreCertificateErrors)
        {
            ServicePointManager.ServerCertificateValidationCallback += AcceptAllCertificatePolicy;
        }

        var response = (HttpWebResponse)request.GetResponse();


    if (response != null)
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                return reader.ReadToEnd();
            }
        }

当传递的语言是英语时,这非常有效,但当传递的语言是西班牙语时,我会在返回的内容中得到大量 � 。

代码是否有问题,或者我缺少什么编码方式?

I am using a HttpWebRequest to read in a web page using the following code:

 var pageurl = new Uri(url, UriKind.Absolute);

        var request = (HttpWebRequest)WebRequest.Create(pageurl);
        request.Method = "GET";
        request.AutomaticDecompression = DecompressionMethods.GZip;
        request.KeepAlive = false;
        request.ConnectionGroupName = Guid.NewGuid().ToString();
        request.ServicePoint.Expect100Continue = false;
        request.Pipelined = false;
        request.MaximumResponseHeadersLength = 4;

        if (ignoreCertificateErrors)
        {
            ServicePointManager.ServerCertificateValidationCallback += AcceptAllCertificatePolicy;
        }

        var response = (HttpWebResponse)request.GetResponse();


    if (response != null)
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                return reader.ReadToEnd();
            }
        }

This works perfectly when the language being passed is english but when another language such as spanish then I get numerous � in the returned content.

Is there a problem with the code or is there something encoding wise I am missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮萍、无处依 2024-11-15 22:18:15

您必须为要下载到 StreamReader 的页面指定正确的编码。例如,如果页面采用 ISO-8859-2 编码,则使用

new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("ISO-8859-2"))

You have to specify the correct encoding for the page you're downloading to StreamReader. For example, if the page is in the encoding ISO-8859-2, use

new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("ISO-8859-2"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文