提交Web表单并获得响应数据在C# [英] Submit web form and get response data in C#

查看:172
本文介绍了提交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 "";
    }
}

这篇关于提交Web表单并获得响应数据在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆