使用C#傳送POST請求

鴨脖發表於2012-04-22

這裡我們要傳送一個POST請求,並接受返回的資料:

namespace Yelbosh{

class Post{

static void main(string[] args){

sentence = "你好吧";

Encoding encoding = Encoding.GetEncoding("UTF-8");

Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
         
        string url = "http://1.caunion.sinaapp.com/a.php";
            HttpWebRequest request = null;
            HttpWebResponse response = null;


// 準備請求,設定引數
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType ="application/x-www-form-urlencoded";
           
            byte[] data = encoding.GetBytes(url + "&sentence="+sentence);
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Flush();
            outstream.Close();
            //傳送請求並獲取相應回應資料


            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程式才開始向目標網頁傳送Post請求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回結果網頁(html)程式碼


            string content = sr.ReadToEnd();

}

}

}

HttpWebRequest在初始化的時候要先根據url進行建立,然後再設定Method和ContentType,然後再將請求的內容寫進去,通過GetRequestStream來返回流,再向這個流中寫請求內容便可以了。再通過request物件的GetResponse方法返回response物件,最後得到返回的資料流,這是通過GetResponseStream方法返回的,最後從這個流中讀出返回的資料便ok了。

相關文章