以编程方式将数据发布到Web表单时出现乱码的httpWebResponse字符串

我试图搜索之前关于这个问题的讨论,但我找不到一个,也许是因为我没有使用正确的关键字。

我正在编写一个小程序,将数据发布到网页上并获得响应。 我发布数据的网站没有提供API。 经过一些谷歌搜索后,我开始使用HttpWebRequest和HttpWebResponse。 代码如下所示:

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://www.site.com/index.aspx"); CookieContainer cookie = new CookieContainer(); httpRequest.CookieContainer = cookie; String sRequest = "SomeDataHere"; httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; httpRequest.Headers.Add("Accept-Encoding: gzip, deflate"); httpRequest.Headers.Add("Accept-Language: en-us,en;q=0.5"); httpRequest.Headers.Add("Cookie: SomecookieHere"); httpRequest.Host = "www.site.com"; httpRequest.Referer = "https://www.site.com/"; httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1"; httpRequest.ContentType = "application/x-www-form-urlencoded"; //httpRequest.Connection = "keep-alive"; httpRequest.ContentLength = sRequest.Length; byte[] bytedata = Encoding.UTF8.GetBytes(sRequest); httpRequest.ContentLength = bytedata.Length; httpRequest.Method = "POST"; Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytedata, 0, bytedata.Length); requestStream.Flush(); requestStream.Close(); HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse(); string sResponse; using (Stream stream = httpWebResponse.GetResponseStream()) { StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("iso-8859-1")); sResponse = reader.ReadToEnd(); } return sResponse; 

我用firefox的firebug来获取标题和数据。

我的问题是,当我使用字符串存储和显示响应时,我得到的都是乱码,如:

 ?????*??????xV?J-4Si1?]R?r)f?|??;????2+g???6?N-?????7??? ?6?? x???qv ??? j?Ro??_*?e*??tZN^? 4s?????? ??Pwc??3???|??_????_??9???^??@?Y??"?k??,?a?H?Lp?A?$ ;???C@????e6'?N???L7?j@???ph??y=?I??=(e?V?6C?? 

通过使用FireBug读取响应头我得到了响应的内容类型:

 Content-Type text/html; charset=ISO-8859-1 

它反映在我的代码中。 我甚至尝试过其他编码,如utf-8和ascii,仍然没有运气。 也许我的方向错了。 请指教。 一个小的代码片段会更好。 谢谢。

您告诉服务器您可以使用httpRequest.Headers.Add("Accept-Encoding: gzip, deflate");接受压缩响应httpRequest.Headers.Add("Accept-Encoding: gzip, deflate"); 。 尝试删除该行,您应该得到明确的文本响应。

如果你想允许压缩响应,HttpWebRequest确实内置了对gzip和deflate的支持 。 删除Accept-Encoding标题行,并将其替换为

 httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate 

这将为您添加适当的Accept-Encoding标头,并在您收到时自动解压缩内容。