程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# Post方式傳輸報文,和處理響應,

C# Post方式傳輸報文,和處理響應,

編輯:C#入門知識

C# Post方式傳輸報文,和處理響應,


 1   public string DoPost(string url, string data)
 2         {
 3             HttpWebRequest req = GetWebRequest(url, "POST");
 4             byte[] postData = Encoding.UTF8.GetBytes(data);
 5             Stream reqStream = req.GetRequestStream();
 6             reqStream.Write(postData, 0, postData.Length);
 7             reqStream.Close();
 8             HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
 9             Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
10             return GetResponseAsString(rsp, encoding);
11         }
12 
13         public HttpWebRequest GetWebRequest(string url, string method)
14         {
15             HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
16             req.ServicePoint.Expect100Continue = false;
17             req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
18             req.ContentType = "text/json";
19             req.Method = method;
20             req.KeepAlive = true;
21             req.UserAgent = "mysoft";
22             req.Timeout = 1000000;
23             req.Proxy = null;
24             return req;
25         }
26 
27         public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
28         {
29             StringBuilder result = new StringBuilder();
30             Stream stream = null;
31             StreamReader reader = null;
32             try
33             {
34                 // 以字符流的方式讀取HTTP響應
35                 stream = rsp.GetResponseStream();
36                 reader = new StreamReader(stream, encoding);
37                 // 每次讀取不大於256個字符,並寫入字符串
38                 char[] buffer = new char[256];
39                 int readBytes = 0;
40                 while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
41                 {
42                     result.Append(buffer, 0, readBytes);
43                 }
44             }
45             finally
46             {
47                 // 釋放資源
48                 if (reader != null) reader.Close();
49                 if (stream != null) stream.Close();
50                 if (rsp != null) rsp.Close();
51             }
52 
53             return result.ToString();
54         }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved