この問題に関する以前の議論を検索しようとしましたが、適切なキーワードを使用しなかったためか、見つかりませんでした。
データを Web ページに投稿して応答を取得する小さなプログラムを作成しています。データを投稿しているサイトは 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 などの他のエンコーディングも試しましたが、まだうまくいきません。多分私は間違った方向にいます。お知らせ下さい。小さなコード スニペットはさらに優れています。ありがとうございます。