0
  1. 登录并创建新的(cookie)会话(systempage.local/login.php)
  2. 如果登录成功,导航到页面并执行某些操作(导航到 systempage.local/index.php)

我正在尝试为本地网络中的站点编写应用程序。
login.php 通常会重定向到 index.php。(在浏览器中)
我已经准备好我的 webrequest 以登录它。(到目前为止有效)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    string sThepage;
    CookieContainer logincookie;

    private void button1_Click(object sender, EventArgs e)
    {
        string strPostData = "user_name=" + txtUser.Text + "&password=" + txtPass.Text + "&language=en&action%3Asubmit=Submit";
        CookieContainer tempCookies = new CookieContainer();

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(strPostData);

        HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("system.local/Login.php");
        postReq.Method = "POST";
        postReq.KeepAlive = true;
        postReq.AllowAutoRedirect = false;
        postReq.Accept = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

        postReq.ContentType = "application/x-www-form-urlencoded";
        postReq.Referer = "system.local/interface/Login.php";
        postReq.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";
        postReq.ContentLength = data.Length;

        Stream postreqStream = postReq.GetRequestStream();
        postreqStream.Write(data, 0, data.Length);
        postreqStream.Close();

        HttpWebResponse postResponse;
        postResponse = (HttpWebResponse)postReq.GetResponse();
        tempCookies.Add(postResponse.Cookies);
        logincookie = tempCookies;

        StreamReader postRegReader = new StreamReader(postResponse.GetResponseStream());
        sThepage = postRegReader.ReadToEnd();

        // Blanksite if login success.
        if (!sThepage.Contains("!doctype"))
        {
            MessageBox.Show("you logged in");
            Navigate(); //Navigate to the index.php
        }
        else
        {
            MessageBox.Show("Client was unable to connect!");    

        }

        richTextBox1.Text = sThepage;
    }
}   
}

..

现在我需要一种导航到索引页(以及其他一些页面)的方法

 private void Navigate()
 {
    // What to do here?
    // and how to keep my cookie(sesion) for the next page?
 }
4

1 回答 1

0

您需要做的是在登录请求完成后,将您发送到变量/文件的 cookie 记录下来,并在每个后续请求中再次发送回相同的 cookie。您可以从标头对象中获取 cookie。

于 2012-08-01T09:38:32.437 回答