22二月/120
使用 HttpWebRequest 實作 POST 方法
前言
有的時候會需要用程式連到某網址把網頁下載回來或是取得資料,如果支援 Get 方法又需要參數的話,可以很簡單的在網址加上參數就可以取得資料了,但是如果只支援 POST 方法的時候我們就沒辦法這樣的處理,得多一點步驟來傳送要 POST 的資料,本文就是要介紹如何使用 HttpWebRequest 來實作 POST 的方法。
實作
首先先簡單設計一個要接收資料用的網站,就簡單寫一個 ASP.Net MVC 的 Action 吧!
1 2 3 4 5 6 7 8 |
[HttpPost] public bool Login(string id, string password) { if (id == "anyun" && password == "pass") return true; else return false; } |
上面程式就是設定只能接收 POST 方法,和傳進去 id 和 password 參數來做基本登陸驗證,最後回傳驗證結果。
接下來就是開一個 Console 程式來實作 POST 方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
static void Main(string[] args) { string Url = "http://localhost:4953/Home/Login"; HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest; string result = null; request.Method = "POST"; // 方法 request.KeepAlive = true; //是否保持連線 request.ContentType = "application/x-www-form-urlencoded"; string param = "id=anyun&password=pass"; byte[] bs = Encoding.ASCII.GetBytes(param); using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } using (WebResponse response = request.GetResponse()) { StreamReader sr = new StreamReader(response.GetResponseStream()); result = sr.ReadToEnd(); sr.Close(); } Console.WriteLine(result); Console.ReadKey(); } |
程式很簡單,有幾點要注意的,就是在將參數 param 做編碼的時候,我這邊因為都是字母,所以就用 ASCII 做編碼,如果要傳輸中文的話就要看 Server 的編碼了,不然中文的話可能就沒辦法接受正確的中文字。
結論
最近 ASP.Net MVC4 Beta 推出,其中包含了 WEB API ,可以讓我們很快速的建立 Service ,這時候如果需要透過程式來接收資料,就可以使用這樣的實作來接收我們要的資料再做處理,因此就花點時間介紹了實作的方式。希望對大家有所幫助。
Leave a comment