1

我试图搜索有关此问题的先前讨论,但没有找到,可能是因为我没有使用正确的关键字。

我正在编写一个将数据发布到网页并获得响应的小程序。我发布数据的网站不提供 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,但仍然没有运气。也许我走错了方向。请指教。一个小的代码片段会更好。谢谢。

4

1 回答 1

5

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

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

httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate

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

于 2012-08-26T18:54:57.697 回答