向HtmlWeb类添加函数

时间:2015-04-24 08:50:50

标签: c# class html-agility-pack

我想在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);
}

这些函数用于将数据发布到网站,然后获取响应html。

我在添加这些功能方面遇到了一些困难,我想知道如何正确地完成这些功能。

该功能将如下使用:

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

1 个答案:

答案 0 :(得分: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);