使用C#发送POST请求

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

这里我们要发送一个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了。

posted @ 2016-07-29 14:08  离。  阅读(67)  评论(0编辑  收藏  举报