有時候需要自動上網抓取資料並讀取內容,這個小功能還常見的,任何程式語言幾乎都有,以下是Asp.net的範例,C Sharp也適用。
// 定義POST Data
string parame = "token=abc";
byte[] postData = System.Text.Encoding.UTF8.GetBytes(parame);
// 設定表頭與內容
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://localhost:44366/api/test/FormCall");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 30000;
request.ContentLength = postData.Length;
// 送出POST資料
using (System.IO.Stream reqStream = request.GetRequestStream())
{
reqStream.Write(postData, 0, postData.Length);
}
// 接收回傳的資料
string responseStr = "";
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
responseStr = sr.ReadToEnd();
}
}
// 印出接收的資料
Response.Write(responseStr);
Response.End();