(現在 DownloadString で使用しているHTTP 動詞である GET の代わりに) WebClient を POST に引き続き使用できますが、(わずかに) 低レベルのクラス WebRequest および WebResponse を使用する方が簡単であることがわかると思います。
これには 2 つの部分があります。1 つ目はログイン フォームの送信、2 つ目は "Set-cookie" ヘッダーを回復し、それを "Cookie" として GET 要求と共にサーバーに送信することです。サーバーはこのCookieを使用して今後あなたを識別します(そのページが「PHPSESSID」を含むSet-cookieヘッダーを返すため、Cookieベースの認証を使用していると確信しています)。
ログインフォームへの投稿
フォーム投稿は簡単にシミュレートできます。投稿データを次のようにフォーマットするだけです。
field1=value1&field2=value2
Scott Hanselmanから改作した WebRequest とコードを使用して、フォーム データをログイン フォームに POST する方法は次のとおりです。
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
ログイン フォームの Set-cookie ヘッダーに表示される内容の例を次に示します。
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
ログインフォームの背後にあるページを取得する
これで、ログインが必要なページに対して GET リクエストを実行できます。
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
編集:
最初の POST の結果を表示する必要がある場合は、返された HTML を次のように復元できます。
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
これを直下に配置cookieHeader = resp.Headers["Set-cookie"];
し、pageSource に保持されている文字列を調べます。