提交Web表单并获得响应数据在C#

问题描述:

我试图写一个C#应用程序,可以自动发送用户ID,密码和登录(提交的登录按钮),以一个网站(例如的 http://abc.com )和HttpRequest都有返回的数据。我怎么做?我stucking ...感谢您的任何建议! :D

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

我使用这些功能...结果
有了第一个可以传递参数与数组名称和参数值,与第二你可以通过整个字符串。结果
记住,这个工程(它返回的HTML页面,你可以请你解析)如果没有之前的JavaScript代码执行后..所以好好看看网页源。

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 "";
    }
}