我尝试搜索之前关于此问题的讨论,但我找不到一个,也许是因为我没有使用正确的关键字。
我正在编写一个小程序,将数据发布到网页上并获得响应。我发布数据的网站未提供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???q v ??? 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,仍然没有运气。也许我的方向错了。 请指教。一个小的代码片段会更好。 谢谢你。
答案 0 :(得分:5)
您告诉服务器您可以接受httpRequest.Headers.Add("Accept-Encoding: gzip, deflate");
的压缩响应。尝试删除该行,您应该得到一个明确的文本响应。
如果要允许压缩响应,HttpWebRequest确实有built in support for gzip and deflate。删除Accept-Encoding标题行,并将其替换为
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
这将为您添加适当的Accept-Encoding标头,并在您收到内容时自动解压缩内容。