8

我对在 C# 中处理网页比较陌生。我要做的是登录特定网站(https://www15.swalife.com/PortalWeb/portal/cwaLogon.jsp)并允许将页面重定向到默认页面,然后从那里导航到( https://www15.swalife.com/csswa/ea/plt/accessELITT.do)并下载源代码并将其输出为字符串。

我已经想出了如何通过 HTTPWebRequest 和 HTTPWebResponse 下载源代码,但是在编写登录功能时遇到了麻烦。我想我将不得不对 POST 做点什么?我也看过http://www.dreamincode.net/forums/topic/152297-c%23-log-in-to-website-programmatically/

提前致谢!!

编辑:

jimmyjambles 提供的代码完美无缺,但它并没有完全得到我想要的页面的源代码。该代码表明登录过程失败,但我相信通过一些调整我可以让它工作......也适用于每个有问题的人:

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications);

尝试将“公共字符串”和“公共布尔”函数分别更改为“公共静态字符串”和“公共静态布尔”:)

编辑2:

响应 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"
4

2 回答 2

7

为了在登录后使用 HttpWebRequest 访问辅助 URL,您需要记住一些事情。

首先,正如 Casperah 提到的,您需要检查登录表单并确定用于接收登录数据的控件的“名称”属性。

完成此操作后,您将需要相应地格式化帖子字符串并将其提供给 WebRequest。

最后一个考虑是,一旦您登录,您将需要存储和维护从保持您登录的服务器分配给您的 cookie。

我从这篇 msdn 文章中获取了一个 WebRequest 片段,并对其进行了修改以在登录后执行第二个页面请求。

        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;
    }

唯一添加的行是 postData 和 cookie。

您将需要修改该行

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

基于您在表单上的控件,因为您发布了您尝试使用的网站,我猜您可能正在寻找

string postData = String.Format("uid={0}&portalBase=cwa&password={1}", username, password);
于 2012-06-08T19:31:09.867 回答
0

在表单中使用 WebBrowser 相当容易。首先导航到 cwaLogon.jsp 页面并找到输入控件并调用提交按钮上的“单击”。要么使用 HTTPWebRequest 和 Response 进行适当的 GET/POST。使用 Fiddler2 检查要发布的内容是一个很好的开始。

于 2012-06-08T18:43:43.203 回答