登录到通过C#网站,导航到另一个网页,然后输出源$ C ​​$ C作为一个字符串 [英] Logging into a website via C#, navigating to another web page, and then output the source code as a string

查看:226
本文介绍了登录到通过C#网站,导航到另一个网页,然后输出源$ C ​​$ C作为一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的,在C#中的网页的工作。我所要做的就是登录到特定网站(<一href="https://www15.swalife.com/PortalWeb/portal/cwaLogon.jsp">https://www15.swalife.com/PortalWeb/portal/cwaLogon.jsp ),并允许在网页被重定向到默认页面,然后从那里导航到(https://www15.swalife.com/csswa/ea/plt/accessELITT.do)和下载源$ C ​​$ c和输出它为一个字符串。

我已经找到了如何下载通过HttpWebRequest和HTTPWebResponse源$ C ​​$ C,但我对编码记录在功能上有问题。我想我会做一些与POST?我已经看过<一href="http://www.dreamin$c$c.net/forums/topic/152297-c%23-log-in-to-website-programmatically/">http://www.dreamin$c$c.net/forums/topic/152297-c%23-log-in-to-website-programmatically/也。

在此先感谢!!

编辑:

由jimmyjambles提供的code完美的作品,但它并没有完全得到我我想要的页面的源代码code。在code暗示的登录过程中失败了,但我相信有调整,我可以得到它的工作一点点......也对大家有问题的:

  ServicePointManager.ServerCertificateValidationCallback =新RemoteCertificateValidationCallback(AcceptAllCertifications);
 

试着改变你的公共字符串和公布尔功能,以公共静态字符串和公共静态布尔分别为:)

编辑2:

响应HTML:

 &LT; D​​OCTYPE HTML PUBLIC \! -  // W3C // DTD HTML 4.01过渡// EN \&GT; \ N'LT; HTML&GT; \ N'LT; HEAD&GT; \ñ \ñ\ñ\ñ\ñ\ñ\ñ&LT; META HTTP-当量= \内容类型\内容= \text / html的;字符集= ISO-8859-1 \&GT; \ N'LT; META NAME = \发电机\内容= \IBM的WebSphere Studio \&GT; \ N'LT; TITLE&GT; endSession.jsp&LT; / TITLE&GT; \ N'LT; LINK REL = \样式\的href = \eipPortletStyles / swalife.css \型= \文/ CSS \&GT; \ñ\ T&LT;脚本类型= \文/ JavaScript的\语言= \的JavaScript \ \ñ\ t \台橡= \eipCommonJavaScript / eipGeneralFunctions.js \/&GT;&LT; / SCRIPT&GT; \ñ\ t \ t \ñ&LT;脚本类型= \文/ JavaScript的\&GT; \ñ\ñ\ tfunction refreshParent()\ñ\ t {\ñ\ t如果(window.parent)\ñ\ t {\ñ\ t如果(window.parent.name =='appMainFrame')\ñ\ t window.parent.location = \/ csswa / EA / PLT / logout.do \; \ñ\ t //警报('您的会话已过期,请重新登录。'); \ñ\ t} \ñ\ t} \ñ\ N'LT; / SCRIPT&GT; \ N'LT; / HEAD&GT; \ N'LT; BODY的onload = \refreshParent(); \&GT; \ñ\ñ\ t \ T&LT; D​​IV CLASS = \eipErrors \&GT; \ñ\ t \ t \ T&LT; D​​IV CLASS = \legendLabel \&gt;消息&LT; / DIV&GT; \ñ\ t \ t \ t \ñ\ t \ t \ T&LT; D​​IV CLASS = \errorsHeader formTitle \&gt;您已经退出缺货船员Web访问&LT; BR&GT; \ t \ t \ t \ñ\ t \ t \ T&LT; / DIV&GT; \ñ\ t \ t \ t \ñ\ t \ t \ T&LT; D​​IV类= \errorsHeader formTitle \&GT;请关闭此窗口和&lt;字体大小= \+ 1 \&GT;注销SWALife&LT的; / FONT&GT;要完成注销过程。 &LT; / DIV&GT; \ñ\ t \ T&LT; D​​IV CLASS = \errorsText \&GT; \ñ\ t \ T&放大器; NBSP; \ñ\ t \ t \ t \ t \ñ\ t \ T&LT; / DIV&GT; \ñ\ t \ t \ñ\ t \ t \ t \ñ\ t \ t \ñ\ t \ T&LT; D​​IV CLASS = \errorsFooter \&gt;您将需要重新继续之前登录&LT。 ; / DIV&GT; \ t \ñ\ t \ t \ñ\ T&LT; / DIV&GT; \ñ\ñ&LT; / BODY&GT; \ N'LT; / HTML&GT; \ N
 

解决方案

为了使用的HttpWebRequest登录后才能访问一个辅助URL,你需要记住几件事情。

首先作为Casperah提到,你将需要检查的登录表单,并确定了名用于接收的登录数据控件的属性。

一旦你做到了这一点,你需要相应地格式化后的字符串,并将其提供给WebRequest的。

最后考虑的是,一旦你登录后,你将需要存储和维护的,让你在登录服务器分配给您的饼干。

我已经从这个MSDN文章一个WebRequest的片段,并修改了它进行第二次登录后,页面请求。

 字符串loginurl =htt​​p://www.gmail.com;
        字符串secondurl =htt​​p://mail.google.com/$p$pfs;

        字符串的用户名=bob@gmail.com;
        字符串密码=12345;
        GetSecondaryLoginPage(loginurl,secondurl,用户名,密码);



    公共字符串GetSecondaryLoginPage(字符串loginurl,串secondurl,用户名字符串,字符串密码,串cookieName = NULL)
    {
        //创建使用,它可以接收后的URL的请求。
        HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(loginurl);
        //请求POST的方法属性设置。
        request.Method =POST;

        的CookieContainer集装箱=新的CookieContainer();

        如果(cookieName!= NULL)
            container.Add(新的Cookie(cookieName,用户名,/,新的URI(loginurl)。主持人));

        request.CookieContainer =容器;

        //创建POST数据并将其转换为一个字节数组。相应地修改这一行
        字符串POSTDATA =的String.Format(用户名= {0}&放大器;密码= {1},用户名,密码);

        ServicePointManager.ServerCertificateValidationCallback =新System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

        字节[]的字节数组= Encoding.UTF8.GetBytes(POSTDATA);
        //了的WebRequest的ContentType属性设置。
        request.ContentType =应用/的X WWW的形式urlen codeD;
        //设置的WebRequest的CONTENTLENGTH财产。
        request.ContentLength = byteArray.Length;
        //获取请求流。
        流式传输的数据流= request.GetRequestStream();
        //将数据写入请求流。
        dataStream.Write(字节数组,0,byteArray.Length);
        //关闭Stream对象。
        dataStream.Close();
        //得到响应。
        WebResponse的响应= request.GetResponse();
        //获取服务器返回的包含流内容。
        数据流= response.GetResponseStream();
        //打开使用一个StreamReader为方便流。
        StreamReader的读者=新的StreamReader(数据流);
        //读取内容。
        字符串responseFromServer = reader.ReadToEnd();

        使用(StreamWriter的OUTFILE =
        新的StreamWriter(output.html))
        {
            outfile.Write(responseFromServer.ToString());
        }

        //清理流。
        reader.Close();
        dataStream.Close();
        response.Close();

        请求=(HttpWebRequest的)WebRequest.Create(secondurl);
        request.CookieContainer =容器;

        响应= request.GetResponse();
        //获取服务器返回的包含流内容。
        数据流= response.GetResponseStream();
        //打开使用一个StreamReader为方便流。
        读者=新的StreamReader(数据流);
        //读取内容。
        responseFromServer = reader.ReadToEnd();

        //清理流。
        reader.Close();
        dataStream.Close();
        response.Close();

        返回responseFromServer;
    }


    公共BOOL AcceptAllCertifications(对象发件人,System.Security.Cryptography.X509Certificates.X509Certificate认证,System.Security.Cryptography.X509Certificates.X509Chain链,System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        返回true;
    }
 

唯一添加的行是为POSTDATA和饼干。

您将需要修改的行

 字符串POSTDATA =的String.Format(用户名= {0}&放大器;密码= {1},用户名,密码);
 

根据表格上的控制,因为您发布的网站你想与我合作可以猜测,你可能找

 字符串POSTDATA =的String.Format(UID = {0}&放大器; portalBase = CWA和放大器;密码= {1},用户名,密码);
 

I am relatively new to working with web pages in C#. What I am trying to do is log into a particular website ( https://www15.swalife.com/PortalWeb/portal/cwaLogon.jsp ) and allowing the page to be redirected to the default page, and then navigating from there to (https://www15.swalife.com/csswa/ea/plt/accessELITT.do) and downloading the source code and output it to a string.

I have figured out how to download the source code via HTTPWebRequest and HTTPWebResponse but am having trouble on coding the logging in function. I assume I will have to do something with POST? I have looked at http://www.dreamincode.net/forums/topic/152297-c%23-log-in-to-website-programmatically/ also.

Thanks in advance!!

EDIT:

The code supplied by jimmyjambles works flawlessly, except it doesn't quite get me the source code of the page I wanted. The code suggests that the log-in process failed, but I believe with a little bit of tweaking I could get it to work...also to everyone having issues with:

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications);

Try changing your "public string" and "public bool" functions to "public static string" and "public static bool" respectively :)

EDIT 2:

Response HTML:

"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<HTML>\n<HEAD>\n\n\n\n\n\n\n<META http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n<META name=\"GENERATOR\" content=\"IBM WebSphere Studio\">\n<TITLE>endSession.jsp</TITLE>\n<LINK rel=\"stylesheet\" href=\"eipPortletStyles/swalife.css\" type=\"text/css\">\n\t<script type=\"text/javascript\" language=\"JavaScript\" \n\t\tsrc=\"eipCommonJavaScript/eipGeneralFunctions.js\"/> </script>\n\t\t\n<script type=\"text/javascript\">\n\n\tfunction refreshParent()\n\t{\n\t    if(window.parent)\n\t    {\n\t    if(window.parent.name == 'appMainFrame')\n\t       window.parent.location = \"/csswa/ea/plt/logout.do\";\n\t    //  alert('Your session has expired.  Please login again. ');\n\t    }\n\t}\n\n</script>\n</HEAD>\n<BODY onload=\"refreshParent();\">\n \n\t \t<div class=\"eipErrors\">\n  \t\t\t<div class=\"legendLabel\">Message</div>\n  \t\t\t\n  \t\t\t    <div class=\"errorsHeader formTitle\">You Have Exited Out of Crew Web Access.<br>  \t\t\t \n  \t\t\t    </div>\n  \t\t\t \n  \t\t\t<div class=\"errorsHeader formTitle\"> Please Close this Window and <font  size=\"+1\">Log Out of SWALife</font> to Complete the Log Out Process.  </div>\n  \t\t<div class=\"errorsText\">\n  \t\t  &nbsp;\n  \t\t\t\t\n  \t\t</div>\n  \t\t\n  \t\t\t\n  \t\t\n  \t\t<div class=\"errorsFooter\">You will need to log back in before continuing.</div>  \t\n  \t\t\n \t</div>\n  \n</BODY>\n</HTML>\n"

解决方案

In order to use HttpWebRequest to access a secondary URL after login you will need to keep in mind a few things.

Firstly as Casperah has mentioned you will need to inspect the login form and identify the "name" attribute of the controls used to receive the login data.

Once you have done this you will need to format a post string accordingly and provide it to the WebRequest.

The last consideration is that once you have logged in, you will need to store and maintain the cookie assigned to you from the server that keeps you logged in.

I have taken a WebRequest snippet from this msdn article and modified it to perform a second page request after the login.

        string loginurl = "http://www.gmail.com";
        string secondurl = "http://mail.google.com/prefs";

        string username = "bob@gmail.com";
        string password = "12345";
        GetSecondaryLoginPage(loginurl, secondurl, username, password);



    public string GetSecondaryLoginPage(string loginurl, string secondurl, string username, string password, string cookieName = null)
    {
        // Create a request using a URL that can receive a post. 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginurl);
        // Set the Method property of the request to POST.
        request.Method = "POST";

        CookieContainer container = new CookieContainer();

        if (cookieName != null)
            container.Add(new Cookie(cookieName, username, "/", new Uri(loginurl).Host));

        request.CookieContainer = container;

        // Create POST data and convert it to a byte array.  Modify this line accordingly
        string postData = String.Format("username={0}&password={1}", username, password);

        ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();

        using (StreamWriter outfile =
        new StreamWriter("output.html"))
        {
            outfile.Write(responseFromServer.ToString());
        }

        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

        request = (HttpWebRequest)WebRequest.Create(secondurl);
        request.CookieContainer = container;

        response = request.GetResponse();
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        reader = new StreamReader(dataStream);
        // Read the content.
        responseFromServer = reader.ReadToEnd();

        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }


    public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

The only added lines are for the postData and cookies.

You will need to modify the line

string postData = String.Format("username={0}&password={1}", username, password);

based on your controls on the form, since you posted the site your trying to work with I can guess that you are probably looking for

string postData = String.Format("uid={0}&portalBase=cwa&password={1}", username, password);

这篇关于登录到通过C#网站,导航到另一个网页,然后输出源$ C ​​$ C作为一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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