c# - 无法使用 HttpWebRequest/HttpWebResponse 下载 html 字符串

标签 c# html httpwebrequest httpwebresponse

我使用 HttpWebRequest/HttpWebResponse 获取 html 文档,下面的代码正在运行,但我无法将接收到的流编码为 html 字符串:

        string uri = "https://myfavoritesite.come";
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
        webrequest.KeepAlive = true;
        webrequest.Method = "GET";
        webrequest.ContentType = "text/html";
        webrequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        //webrequest.Connection = "keep-alive";
        webrequest.Host = "cat.sabresonicweb.com";
        webrequest.Headers.Add("Accept-Encoding", "gzip, deflate");
        webrequest.Headers.Add("Accept-Language", "en-US,en;q=0.5");
        webrequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0";

        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

        Console.Write(webresponse.StatusCode);
        Stream receiveStream = webresponse.GetResponseStream();


        Encoding enc = System.Text.Encoding.GetEncoding(1252);//1252
        StreamReader loResponseStream = new
          StreamReader(receiveStream, enc);

        string Response = loResponseStream.ReadToEnd();

        loResponseStream.Close();
        webresponse.Close();

        Console.Write(Response);

所以,我使用下面的代码行来测试是否有成功的请求。

         Console.Write(webresponse.StatusCode);

屏幕上的结果是好的,这意味着请求已发送,但屏幕上显示的响应字符串不是 html 格式,这很奇怪,像这样:@32u%&$&( @*#Eeeuw

最佳答案

通过使用 webrequest.Headers.Add("Accept-Encoding", "gzip, deflate");,您是在告诉服务器您了解压缩响应。删除该 header 并使用普通的 UTF8 编码而不是您正在使用的 1252。然后你应该得到正确的字符串。您可以只使用 System.Text.Encoding.UTF8

关于c# - 无法使用 HttpWebRequest/HttpWebResponse 下载 html 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14641201/

相关文章:

html - 如何在 iPhone 上显示邮件摘要

html - 为什么我的页脚不在页面底部?

C# HttpWebRequest 响应错误(401)

c# - 带有 "infinite scrolling"页面的 httpwebrequest?

c# - VS Code 中的智能感知/代码完成对 XML 没有帮助

c# - Resharper 快速修复模板

html - 页脚在上方,当我将浮点值设置为正确时

php - youtube API出现403错误

c# - 无法在 System.Boolean 上进行测试

c# - 使用 Bootstrap Datepicker 选择 future 日期并将其传递给 ASP.NET MVC Controller