c# Post数据到web服务器

c# Post数据到web服务器

代码如下:

 1         /// <summary>
 2         /// Post数据到网站
 3         /// </summary>
 4         /// <param name="posturl">网址</param>
 5         /// <param name="postData">参数</param>
 6         /// <returns></returns>
 7         public string GetPage(string posturl, string postData)
 8         {
 9             Stream outstream = null;
10             Stream instream = null;
11             StreamReader sr = null;
12             HttpWebResponse response = null;
13             HttpWebRequest request = null;
14             Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
15             byte[] data = encoding.GetBytes(postData);
16             // 准备请求...
17             try
18             {
19                 // 设置参数
20                 request = WebRequest.Create(posturl) as HttpWebRequest;
21                 CookieContainer cookieContainer = new CookieContainer();
22                 request.CookieContainer = cookieContainer;
23                 request.AllowAutoRedirect = true;
24                 request.Method = "POST";
25                 request.ContentType = "application/x-www-form-urlencoded";
26                 request.ContentLength = data.Length;
27                 outstream = request.GetRequestStream();
28                 outstream.Write(data, 0, data.Length);
29                 outstream.Close();
30                 //发送请求并获取相应回应数据
31                 response = request.GetResponse() as HttpWebResponse;
32                 //直到request.GetResponse()程序才开始向目标网页发送Post请求
33                 instream = response.GetResponseStream();
34                 sr = new StreamReader(instream, encoding);
35                 //返回结果网页(html)代码
36                 string content = sr.ReadToEnd();
37                 string err = string.Empty;
38                 return content;
39             }
40             catch (Exception ex)
41             {
42                 string err = ex.Message;
43                 return string.Empty;
44             }
45         }

c# Post数据到web服务器,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。