Submit web form and get response data in C#

2019-04-14 12:20发布

问题:

I'm trying to write an C# application that can automatically send user id, password and login (submit the "Login" button) to a website (example http://abc.com) and get data returned in Httprequest. How do i do that? I'm stucking... Thanks for any your recommend! :D

回答1:

I use these functions...
With first you can pass an array with param name and param value, with second you can pass the whole string.
Bear in mind that this works (it returns HTML page that you can parse as you please) if POST is executed without javascript code before... so take a good look to web page source.

public static string HttpPost(string url, object[] postData, string saveTo = "")
{
    StringBuilder post = new StringBuilder();
    for (int i = 0; i < postData.Length; i += 2)
        post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
    return HttpPost(url, post.ToString(), saveTo);
}
public static string HttpPost(string url, string postData, string saveTo = "")
{
    postData = postData.Replace("\r\n", "");
    try
    {
        WebRequest req = WebRequest.Create(url);
        byte[] send = Encoding.Default.GetBytes(postData);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        //req.ContentType = "text/xml;charset=\"utf-8\"";
        req.ContentLength = send.Length;

        Stream sout = req.GetRequestStream();
        sout.Write(send, 0, send.Length);
        sout.Flush();
        sout.Close();

        WebResponse res = req.GetResponse();
        StreamReader sr = new StreamReader(res.GetResponseStream());
        string returnvalue = sr.ReadToEnd();
        if (!string.IsNullOrEmpty(saveTo))
            File.WriteAllText(saveTo, returnvalue);

        //Debug.WriteLine("{0}\n{1}", postData, returnvalue);
        return returnvalue;
    }
    catch (Exception ex)
    {
        Debug.WriteLine("POST Error on {0}\n  {1}", url, ex.Message);
        return "";
    }
}