簡體   English   中英

以編程方式將數據發布到Web表單時出現亂碼的httpWebResponse字符串

[英]Garbled httpWebResponse string when posting data to web form programmatically

我嘗試搜索有關此問題的先前討論,但沒有找到一個討論,可能是因為我沒有使用正確的關鍵字。

我正在編寫一個小程序,該程序將數據發布到網頁並獲得響應。 我向其發布數據的網站沒有提供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,仍然沒有運氣。 也許我走錯了方向。 請指教。 一個小的代碼片段會更好。 謝謝。

您告訴服務器可以使用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標頭,並在接收到內容時自動對其進行解壓縮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM