WebClient登录问题C#

时间:2014-10-21 21:15:11

标签: c# login webclient

<form name="login" action="https://www.Testsite.com/html/login.jsp" method="post">
    <div>
        <input type="hidden" name="action" value="login">
        <input type="text" name="login_name" id="login_name" autocomplete="username" placeholder="User Name">
        <input type="password" name="password" id="password" autocomplete="current-password" placeholder="Password">
        <input type="hidden" name="user_key" value="-963293021">
        <input type="submit" id="html_login_btn" value="Login">
        <div>
            <input type="checkbox" name="remember" id="remember" checked="true">
            <label for="remember">Remember me</label>
            <a href="/html/forgot_name.jsp">Forgot User Name?</a>
            <a href="/html/forgot.jsp">Forgot Password?</a>
        </div>
    </div>
</form>

我正在尝试使用webclient登录网站,我已经制作了一个刮刀进行测试,但我想尝试刮擦的页面要求用户在查看页面之前登录。我遇到的问题是当我尝试登录时尝试下载login.jsp文件。我在这个网站上看了几篇文章,介绍了如何做,以及我如何编写下面的代码。我不想要答案,因为我试图学习这个。

如果你回复一个解决方案,你可以指出我做错了什么,这是我用来尝试登录的代码:

using (WebClient client = new WebClient())
{
    try
    {
        System.Collections.Specialized.NameValueCollection collection =
        new System.Collections.Specialized.NameValueCollection();
        collection.Add("login_name", "ImUser");
        collection.Add("password", "Thispass");
        client.Proxy = null;
        byte[] result = client.UploadValues("http://www.Testsite.com/html/login.jsp", "post", collection);
        System.IO.File.WriteAllBytes("login.jsp", result);
        System.Diagnostics.Process.Start("login.jsp");
    }
    catch (WebException e)
    {
        Console.WriteLine(e.Status);
    }
}

编辑:

public Form1()
{
    InitializeComponent();
    string loginData = "login_name=ImUser&passowrd=ThisPas&next=/";

    WebClient web = new WebClient();

    web.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
    web.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    web.Headers.Add("Accept-Encoding", "identity");
    web.Headers.Add("Accept-Language", "en-US,en;q=0.8");
    web.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
    web.Headers.Add("ContentType", "application/x-www-form-urlencoded");
    string response = web.UploadString("https://www.testsite.com/html/login.jsp", "POST", loginData);
}

private void button1_Click(object sender, EventArgs e)
{
    List<string> players = new List<string>();
    WebClient web = new WebClient();
    String html = web.DownloadString("http://www.testsite.com");
    MatchCollection m1 = Regex.Matches(html, @"<a href=""\s*(.+?)\s*"">", RegexOptions.Singleline);

    foreach (Match m in m1)
    {
        if (m.Groups[1].Value != "")
        {
            string player = m.Groups[1].Value;
            players.Add(player);
        }
    }
    listbox1.DataSource = players; 
}

0 个答案:

没有答案