0%

【C#】Server端透過POST資料到API

之前POST資料都是在Client端無論是用JQuery的AJAX或是Form的方式,今天學會如何從Server端POST資料到指定的頁面,記錄一下程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Post資料到Web
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(WebURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

//將要傳遞的資料PostData轉成Byte陣列並寫入request
byte[] byWordWriteroPost = encoding.GetBytes(PostData);
request.ContentLength = byWordWriteroPost.Length;
Stream stream = request.GetRequestStream();
stream.Write(byWordWriteroPost, 0, byWordWriteroPost.Length);
stream.Close();

//取得網頁結果
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
string returnString = reader.ReadToEnd();
response.Close();