C# 应用程序登录网站失败

C# 应用程序登录网站失败,c#,winforms,cookies,login,httpwebrequest,C#,Winforms,Cookies,Login,Httpwebrequest,我的目标是使用我的应用程序登录,我是C#的新手,我从另一个链接了解了下面的代码,但我无法解决我的问题。调试时,响应显示错误的登录页面,而不是登录成功页面。谁能帮我调查一下我哪里做错了 我使用篡改数据firefox插件来获取这些需要的值,但我不确定是否正确使用了它们 非常感谢你的帮助!谢谢。:) 第1部分: public class CookieAwareWebClient : WebClient { public string Method;

我的目标是使用我的应用程序登录,我是C#的新手,我从另一个链接了解了下面的代码,但我无法解决我的问题。调试时,
响应
显示错误的登录页面,而不是登录成功页面。谁能帮我调查一下我哪里做错了

我使用篡改数据firefox插件来获取这些需要的值,但我不确定是否正确使用了它们

非常感谢你的帮助!谢谢。:)

第1部分:

        public class CookieAwareWebClient : WebClient
    {
        public string Method;
        public CookieContainer CookieContainer { get; set; }
        public Uri Uri { get; set; }

        public CookieAwareWebClient()
            : this(new CookieContainer())
        {
        }

        public CookieAwareWebClient(CookieContainer cookies)
        {
            this.CookieContainer = cookies;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = this.CookieContainer;
                (request as HttpWebRequest).ServicePoint.Expect100Continue = false;
                (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0";
                (request as HttpWebRequest).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                (request as HttpWebRequest).Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.5");
                (request as HttpWebRequest).Referer = "http://uk.advfn.com/";
                (request as HttpWebRequest).KeepAlive = true;
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                if (Method == "POST")
                {
                    (request as HttpWebRequest).ContentType = "application/x-www-form-urlencoded";
                }

            }
            HttpWebRequest httpRequest = (HttpWebRequest)request;
            httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return httpRequest;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            WebResponse response = base.GetWebResponse(request);
            String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

            if (setCookieHeader != null)
            {
                //do something if needed to parse out the cookie.
                try
                {
                    if (setCookieHeader != null)
                    {
                        Cookie cookie = new Cookie(); //create cookie
                        this.CookieContainer.Add(cookie);
                    }
                }
                catch (Exception)
                {

                }
            }
            return response;
        }
    }
第2部分:

        private void btn_login_Click(object sender, EventArgs e)
    {
        var cookieJar = new CookieContainer();
        CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);
        string response = client.DownloadString("http://uk.advfn.com/common/account/login");
        string postData = string.Format("redirect_url=aHR0cDovL3VrLmFkdmZuLmNvbQ%3D%3D&site=uk&login_username=demouser&login_password=demopassword");
        client.Method = "POST";
        response = client.UploadString("https://secure.advfn.com/login/secure", postData);
    }

我将使用fiddler捕获通过浏览器成功登录的http请求,然后将其与应用程序生成的请求进行比较。两者之间的任何差异都可能为应用程序无法成功登录提供线索。

几年前,我曾远程登录过一个网站,并保存了帮助我解决的StackOverflow问题


我找不到我的代码,因为我不是以前在同一家公司工作,但希望这能有所帮助……

我尝试了你的代码,效果很好。我唯一要做的就是更改密码并登录到正确的密码


我猜您出现“错误登录”消息的原因是您实际上输入了错误的登录和密码。

我想我应该更新一下我自己的问题,以便它能够帮助其他人

我最终跳过了所有复杂的代码,我使用Selenium登录了网站,然后下载了我需要的文件。Selenium确实是一个功能强大的工具,我在每次下载中使用一定的时间间隔下载了900多个文件,只需使用Selenium和Firefox即可。特别感谢@VDohnal,他给我留下了一条评论,不幸的是,我只能对他的评论投赞成票,因为他没有“回答”

代码是从Selenium IDE导出的,我对代码做了一些修改,并添加了需要下载的部分

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTests
{
    private IWebDriver driver;
    private StringBuilder verificationErrors;
    private string baseURL;
    private bool acceptNextAlert = true;

    private bool IsElementPresent(By by)
    {
        try
        {
            driver.FindElement(by);
            return true;
        }
        catch (NoSuchElementException)
        {
            return false;
        }
    }

    private bool IsAlertPresent()
    {
        try
        {
            driver.SwitchTo().Alert();
            return true;
        }
        catch (NoAlertPresentException)
        {
            return false;
        }
    }

    private string CloseAlertAndGetItsText()
    {
        try
        {
            IAlert alert = driver.SwitchTo().Alert();
            string alertText = alert.Text;
            if (acceptNextAlert)
            {
                alert.Accept();
            }
            else
            {
                alert.Dismiss();
            }
            return alertText;
        }
        finally
        {
            acceptNextAlert = true;
        }
    }

    public void TheCTest()
    {
        try
        {
            driver = new FirefoxDriver();
            baseURL = "http://uk.advfn.com";
            verificationErrors = new StringBuilder();
            driver.Navigate().GoToUrl(baseURL + "/common/account/login");
            driver.FindElement(By.Id("login_username")).Clear();
            driver.FindElement(By.Id("login_username")).SendKeys("demouser");
            driver.FindElement(By.Id("login_password")).Clear();
            driver.FindElement(By.Id("login_password")).SendKeys("demopass");
            driver.FindElement(By.Id("login_submit")).Click();
            Thread.Sleep(30000);
            //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
            foreach (DataGridViewRow row in dataGridView_FetchTickers.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    try
                    {
                        driver.Navigate().GoToUrl(baseURL + "/p.php?pid=data&daily=0&symbol=L%5E" + row.Cells[1].Value.ToString());
                        //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
                        Thread.Sleep(30000);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                }
                else
                {
                    //Do nothing
                }
            }
        }
        catch (Exception)
        {
            //
        }  
    }

    private void btn_fetchSharePrices_Click(object sender, EventArgs e)
    {
        TheCTest();
    }
}

您是否在cookie容器中提供了正确的cookie来登录?您确定您使用的用户名和密码正确吗?您可以使用.net 4.5吗?也许HttpClinet更容易使用:也许使用SeleniumWebDriver for Firefox可以解决您的问题?如果你感兴趣的话,我可以举个例子。你的应用程序需要打开一个Firefox实例。1.首先将响应变量设置为“”,但不使用它。仅在最后一行将其设置为另一个值。2.URL:不存在。3.如果我尝试使用带有“demouser”和密码“demopassword”的浏览器登录,我会收到一条无效的登录消息Hi Pavel,感谢您的回复。我确实使用了正确的用户名和密码。在使用我的应用程序执行登录任务之前,我已经通过web浏览器进行了尝试。你用的正是我的代码吗?从现在起,我将在22小时内尝试每个人的解决方案/建议,以便奖励正确的人。谢谢。:)我使用的代码与您的消息中列出的代码完全相同。我已将其插入linqPad,更改了登录名:pass并按了run=)在我的实践中出现了一个奇怪的情况,这说明身份验证cookie不是在响应中返回的,而是在请求中返回的。但我不认为这是你的情况。有很好的建议给你,使用fiddler来比较来自浏览器和应用程序的请求。有时甚至1字节也很重要。我不能给你太多帮助,因为在我的机器上无法重现这种行为。