C#通过POST发送数据函数,类似asp中的xmlhttp
1 //purl处理页面,str参数(如:username=admin&passwod=123456)
2
3 //返回处理页面输出的内容
4
5 //使用:string data = PostData("http://www.zhangxun.net/", "action=Fav&str=这个是好网站");
6
7 public static string PostData(string purl,string str)
8 {
9 try
10 {
11 byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
12 // 准备请求
13 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(purl);
14
15 //设置超时
16 req.Timeout = 30000;
17 req.Method = "Post";
18 req.ContentType = "application/x-www-form-urlencoded";
19 req.ContentLength = data.Length;
20 Stream stream = req.GetRequestStream();
21 // 发送数据
22 stream.Write(data, 0, data.Length);
23 stream.Close();
24
25 HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
26 Stream receiveStream = rep.GetResponseStream();
27 Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
28 // Pipes the stream to a higher level stream reader with the required encoding format.
29 StreamReader readStream = new StreamReader(receiveStream, encode);
30
31 Char[] read = new Char[256];
32 int count = readStream.Read(read, 0, 256);
33 StringBuilder sb = new StringBuilder("");
34 while (count > 0)
35 {
36 String readstr = new String(read, 0, count);
37 sb.Append(readstr);
38 count = readStream.Read(read, 0, 256);
39 }
40
41 rep.Close();
42 readStream.Close();
43
44 return sb.ToString();
45
46 }
47 catch (Exception ex)
48 {
49 return "";
50 // ForumExceptions.Log(ex);
51 }
52 }
53
54
2
3 //返回处理页面输出的内容
4
5 //使用:string data = PostData("http://www.zhangxun.net/", "action=Fav&str=这个是好网站");
6
7 public static string PostData(string purl,string str)
8 {
9 try
10 {
11 byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
12 // 准备请求
13 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(purl);
14
15 //设置超时
16 req.Timeout = 30000;
17 req.Method = "Post";
18 req.ContentType = "application/x-www-form-urlencoded";
19 req.ContentLength = data.Length;
20 Stream stream = req.GetRequestStream();
21 // 发送数据
22 stream.Write(data, 0, data.Length);
23 stream.Close();
24
25 HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
26 Stream receiveStream = rep.GetResponseStream();
27 Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
28 // Pipes the stream to a higher level stream reader with the required encoding format.
29 StreamReader readStream = new StreamReader(receiveStream, encode);
30
31 Char[] read = new Char[256];
32 int count = readStream.Read(read, 0, 256);
33 StringBuilder sb = new StringBuilder("");
34 while (count > 0)
35 {
36 String readstr = new String(read, 0, count);
37 sb.Append(readstr);
38 count = readStream.Read(read, 0, 256);
39 }
40
41 rep.Close();
42 readStream.Close();
43
44 return sb.ToString();
45
46 }
47 catch (Exception ex)
48 {
49 return "";
50 // ForumExceptions.Log(ex);
51 }
52 }
53
54