天天看點

利用WebRequest來實作模拟浏覽器通過Post方式向伺服器送出資料

//通過Post發送的資料 

string payload=”chkbook=book&keyword=管理”; 

WebRequest req = WebRequest.Create(”http://localhost/pceo/Search.aspx”); 

req.Method = “POST”; 

req.ContentType = “application/x-www-form-urlencoded”; 

StringBuilder UrlEncoded = new StringBuilder(); 

Char[] reserved = {’?', ‘=’, ‘&’}; 

byte[] SomeBytes = null; 

if (payload != null) 

int i=0, j; 

while(i<payload.Length) 

j=payload.IndexOfAny(reserved, i); 

if (j==-1) 

UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, payload.Length-i),System.Text .Encoding .GetEncoding (”gb2312″))); 

break; 

UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, j-i),System.Text .Encoding .GetEncoding (”gb2312″))); 

UrlEncoded.Append(payload.Substring(j,1)); 

i = j+1; 

SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString()); 

req.ContentLength = SomeBytes.Length; 

Stream newStream = req.GetRequestStream(); 

newStream.Write(SomeBytes, 0, SomeBytes.Length); 

newStream.Close(); 

else 

req.ContentLength = 0; 

try 

WebResponse result = req.GetResponse(); 

Stream ReceiveStream = result.GetResponseStream(); 

Byte[] read = new Byte[512]; 

int bytes = ReceiveStream.Read(read, 0, 512); 

txtHTML.InnerHtml = “”; 

while (bytes > 0) 

// 注意: 

// 下面假定響應使用 UTF-8 作為編碼方式。 

// 如果内容以 ANSI 代碼頁形式(例如,932)發送,則使用類似下面的語句: 

// Encoding encode = System.Text.Encoding.GetEncoding(”shift-jis”); 

Encoding encode = System.Text.Encoding.GetEncoding(”gb2312″); 

txtHTML.InnerHtml = txtHTML.InnerHtml + encode.GetString(read, 0, bytes); 

bytes = ReceiveStream.Read(read, 0, 512); 

catch(Exception) 

txtHTML.InnerHtml = “檢索頁時出錯”; 

}

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1081569

繼續閱讀