2010年9月15日 星期三

如何透過Request的方式,進行Post網頁,並直接解析該請求網頁的內容

有人的做法是用webClient去做,但是保哥提到透過該方法有以下的缺點:

無法指定 Timeout,所以當網路連不上時,網頁或程式會整個停在那裡很久!
不適合用來下載大量的檔案,高負載的網站也不適合這樣用,即便你用非同步的方式撰寫,也會讓WebClient
因為佔據過多 Threads 而導致效能降低,壹台電腦的 Threads 數是有限制的。

對於較正式的場合,還是建議改用 HttpWebRequest 類別處理。

參考源碼如下:

//指定編碼
Encoding myEncoding = Encoding.GetEncoding("big5");

//宣告要post的變數字串
string param = HttpUtility.UrlEncode("FormID", myEncoding) + "=" + HttpUtility.UrlEncode("ACT011", myEncoding) + "&" + HttpUtility.UrlEncode("SheetNo", myEncoding) + "="+HttpUtility.UrlEncode("200900010001", myEncoding) + "&" + HttpUtility.UrlEncode("ParserRoleID", myEncoding) + "=" + HttpUtility.UrlEncode("1", myEncoding) + "&" + HttpUtility.UrlEncode("BranchNo", myEncoding) + "=" + HttpUtility.UrlEncode("0010", myEncoding) + "&"+ HttpUtility.UrlEncode("SerialNo", myEncoding) + "=" + HttpUtility.UrlEncode("01", myEncoding) + "&" + HttpUtility.UrlEncode("FlowID", myEncoding) + "=" + HttpUtility.UrlEncode("1", myEncoding) + "&"+ HttpUtility.UrlEncode("UserID", myEncoding) + "=" + HttpUtility.UrlEncode("3726", myEncoding);

//對post參數進行編碼
byte[] postBytes = Encoding.ASCII.GetBytes(param);

//宣告HttpWebRequest物件,並指派URL對像
HttpWebRequest req = HttpWebRequest)HttpWebRequest.Create("http://localhost/EFSP7/PostTest.aspx");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=big5";
req.ContentLength = postBytes.Length;

發送Request,並寫入Post參數
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(postBytes, 0, postBytes.Length);
}

//取得Request的回傳串流
using (HttpWebResponse wr = req.GetResponse() as HttpWebResponse)
{
StreamReader tSR = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.Default);
string tResult = tSR.ReadToEnd();
tSR.Close();

try
{
Response.Write(tResult);
}
catch (Exception ex)
{
throw ex;
}

}




參考網址:

沒有留言:

張貼留言