1
類
我想一些功能添加到HtmlWeb類,特別是這些:添加功能HtmlWeb
public HtmlDocument SubmitFormValues (NameValueCollection fv, string url)
{
// Attach a temporary delegate to handle attaching
// the post back data
PreRequestHandler handler = delegate(HttpWebRequest request) {
string payload = this.AssemblePostPayload (fv);
byte[] buff = Encoding.ASCII.GetBytes (payload.ToCharArray());
request.ContentLength = buff.Length;
request.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream reqStream = request.GetRequestStream();
reqStream.Write (buff, 0, buff.Length);
return true;
}
this.PreRequest += handler;
HtmlDocument doc = this.Load (url, "POST");
this.PreRequest -= handler;
return doc;
}
private string AssemblePostPayload (NameValueCollection fv)
{
StringBuilder sb = new StringBuilder();
foreach (String key in fv.AllKeys) {
sb.Append ("&" + key + "=" + fv.Get (key));
}
return sb.ToString().Substring (1);
}
這些函數用於POST數據到一個網站,然後獲得響應的HTML。
我一直有一些添加這些功能的困難,我想知道如何正確地做到這一點。
功能將像這樣使用:
HtmlWeb webGet = new HtmlWeb();
NameValueCollection postData = new NameValueCollection (1);
postData.Add ("name", "value");
string url = "url";
HtmlDocument doc = webGet.SubmitFormValues (postData, url);
我不認爲空格會產生錯誤,但它可能有點誤導。 – MazzFraps