从受密码保护的网站自动下载

时间:2010-04-10 14:51:30

标签: c# .net download

我需要一些帮助来分配我的工作项目。目前我们手动访问该站点,登录,然后每个月从供应商的网站下载2个excel文件。然后将文件加载到SQL中。

我们希望自动化此过程。现在将文件加载到SQL我可以做,但我不知道如何自动登录到网站输入我的用户详细信息和收集文件。我主要处理SQL并且只有很少的.NET经验,因此任何代码示例都会受到最高的赞赏。

只是为了确认。登录表单位于aspx页面上。只是一个基本表单,其中包含一个包含用户名和表格的表格密码字段,忘记密码链接和登录按钮

1 个答案:

答案 0 :(得分:4)

您可以使用webclient或httpwebrequest。

Login to the page with HttpWebRequest

How do you login to a webpage and retrieve its content in C#?

Httpwebrequest示例:

    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://sso.bhmobile.ba/sso/login"); 
    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)"; 
    req.Method = "POST";
    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    req.Headers.Add("Accept-Language: en-us,en;q=0.5");
    req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    req.KeepAlive = true;
    req.Headers.Add("Keep-Alive: 300");
    req.Referer ="http://sso.bhmobile.ba/sso/login";

    req.ContentType = "application/x-www-form-urlencoded"; 

    String Username = "username";
    String PassWord = "Password";

    StreamWriter sw = new StreamWriter(req.GetRequestStream());
    sw.Write("application=portal&url=http%3A%2F%2Fwww.bhmobile.ba%2Fportal%2Fredirect%3Bjsessionid%3D1C568AAA1FB8B5C757CF5F68BE6ECE65%3Ftype%3Dssologin%26url%3D%2Fportal%2Fshow%3Bjsessionid%3D1C568AAA1FB8B5C757CF5F68BE6ECE65%3Fidc%3D1023278&realm=sso&userid=" + Username + "&password=" + password + "&x=16&y=11");
    sw.Close();

    HttpWebResponse response = (HttpWebResponse)req.GetResponse();


    StreamReader reader = new StreamReader(response.GetResponseStream());
    string tmp = reader.ReadToEnd();

    foreach (Cookie cook in response.Cookies)
    {
        tmp += "\n" + cook.Name + ": " + cook.Value;
    }


    Response.Write(tmp);
    Response.End();

Webclient示例:

WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username", "password");
string url = "http://foo.com";                  
try
{
        using (Stream stream = wc.OpenRead(new Uri(url)))
        {
                using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
             }
        }
}
catch (WebException e)
{
        //Error handeling
}