Winform 程序以POST形式访问网站

本例介绍了Winform程序发送POST请求访问页面,主要使用到了HttpWebRequest和HttpWebResponse这两个对象。

 

程序主要代码如下:

代码
 1 using System.Net;
2 using System.IO;
3
4
5 //创建HttpWebRequest对象
6 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://192.168.0.1");//目标主机ip地址
7
8 //模拟POST的数据
9 string postData = string.Empty;
10 postData += "user=" + "test1";
11 postData += "&password=" + "123";
12 Encoding utf8=Encoding.UTF8;
13 byte[] data = utf8.GetBytes(postData);
14
15 //设置请求头信息
16 string cookieheader = string.Empty;
17 CookieContainer cookieCon = new CookieContainer();
18 request.Method = "POST";
19 //设置cookie,若没有可以不设置
20 request.CookieContainer = cookieCon;
21 request.ContentType = "application/x-www-form-urlencoded";
22 request.ContentLength = data.Length;
23 Stream newStream = request.GetRequestStream();
24 //把请求数据 写入请求流中
25 newStream.Write(data, 0, data.Length);
26 newStream.Close();
27
28
29 //获得HttpWebResponse对象
30 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
31
32 Console.Write("Content length is {0}", response.ContentLength + "\r\n");
33 Console.Write("Content type is {0}", response.ContentType + "\r\n");
34
35 //获得响应流
36 Stream receiveStream = response.GetResponseStream();
37 StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
38 //输入响应流信息
39 Console.Write("Response stream received.\r\n");
40 Console.Write(readStream.ReadToEnd() + "\r\n");
41
42 response.Close();
43 receiveStream.Close();
44 readStream.Close();

 

你可能感兴趣的:(WinForm)