2015-04-24 145 views
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); 
+0

我不認爲空格會產生錯誤,但它可能有點誤導。 – MazzFraps

回答

1

假設你的方法是正確的,你可以創建自己的類繼承HtmlWeb,把2種方法有:

public class HtmlWebExtended : HtmlWeb 
{ 
    public HtmlDocument SubmitFormValues(NameValueCollection fv, string url) 
    { 
     // Attach a temporary delegate to handle attaching 
     // the post back data 
     ...... 
    } 

    private string AssemblePostPayload(NameValueCollection fv) 
    { 
     ...... 
    } 
} 

然後使用您自己的HtmlWebExtended類代替預定義的HtmlWeb

HtmlWebExtended webGet = new HtmlWebExtended(); 
NameValueCollection postData = new NameValueCollection (1); 
postData.Add("name", "value"); 
string url = "url"; 
HtmlDocument doc = webGet.SubmitFormValues(postData, url); 
+0

我的代碼似乎現在正在工作,謝謝! – MazzFraps