使用C#發送POST請求

轉:http://blog.csdn.net/yelbosh/article/details/7486636

這裏咱們要發送一個POST請求,並接受返回的數據:php

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了。html

相關文章
相關標籤/搜索