@ITの記事のC#でPOSTメソッドほぼ写経。
WebRequest/WebResponseクラスでPOSTメソッドによりデータを送信するには?
http://http://www.atmarkit.co.jp/fdotnet/dotnettips/318webpost/webpost.html
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
class Program
{
static void Main(string[] args)
{
// POSTする対象のURL
string url = "http://www.rarejob.com/login/top.php?mode=off&";
// POSTメソッドで渡すパラメータ
string param = "";
// Dictionaryオブジェクト
var dic = new Dictionary<string, string>();
dic["USER_ID"] = "メールアドレスを指定";
dic["PASSWORD"] = "パスワードを指定";
// POSTメソッドのパラメータ作成
foreach (string key in dic.Keys)
param += String.Format("{0}={1}&", key, dic[key]);
// paramをASCII文字列にエンコードする
byte[] data = Encoding.ASCII.GetBytes(param);
// リクエスト作成
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
// ポストデータをリクエストに書き込む
using (Stream reqStream = request.GetRequestStream())
reqStream.Write(data, 0, data.Length);
// レスポンスの取得
WebResponse response = request.GetResponse();
// 結果の読み込み
string htmlString = "";
using (Stream resStream = response.GetResponseStream())
using(var reader = new StreamReader(resStream, Encoding.GetEncoding("Shift_JIS")))
htmlString = reader.ReadToEnd();
// 結果の出力
Console.WriteLine(htmlString);
Console.Write("Press enter to end:");
Console.ReadLine();
}
}
0 Kommentarer:
コメントを投稿