0

我试图通过多种方式解决这个问题,但我无法让它发挥作用。下面的代码成功地允许用户使用按钮 1 登录,正如我在富文本框中看到的那样。但是,当我按下按钮 2 将我定向到网站上的其他页面时,用户不会保持登录状态。如下所示,我尝试传递 logincookie,但无济于事。我该如何解决这个问题?

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim PostData As String

    Try
        'Logon
        PostData = "username=" & TextBox1.Text & "&password=" & TextBox2.Text
        LogonPage(ConnectURL, logincookie, PostData)

    Catch ex As Exception
        MsgBox(ex.Message.ToString)
    End Try
End Sub


Imports System.Net
Imports System.IO
Imports System.Text

Public Class Form1
    Dim logincookie As CookieContainer
    Const ConnectURL = "http://www.example.com/test/login.php"
    Const HomeURL = "http://www.example.com/test/"

    Private Sub LogonPage(ByVal URL As String, ByRef logincookie As CookieContainer, ByVal PostData As String)
        Dim reader As StreamReader
        Dim tempCookies As New CookieContainer
        Dim Request As HttpWebRequest = HttpWebRequest.Create(URL)

        Request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"
        Request.CookieContainer = tempCookies
        Request.AllowAutoRedirect = True
        Request.ContentType = "application/x-www-form-urlencoded"
        PostData = "username=" & TextBox1.Text & "&password=" & TextBox2.Text
        Request.Method = "POST"
        Request.ContentLength = PostData.Length

        Dim requestStream As Stream = Request.GetRequestStream()
        Dim postBytes As Byte() = Encoding.ASCII.GetBytes(PostData)

        requestStream.Write(postBytes, 0, postBytes.Length)
        requestStream.Close()

        Dim Response As HttpWebResponse = Request.GetResponse()
        tempCookies.Add(Response.Cookies)
        logincookie = tempCookies

        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(Response.GetResponseStream())
        Dim sourcecode As String = sr.ReadToEnd()
        RichTextBox1.Text = sourcecode
        reader = New StreamReader(Response.GetResponseStream())

        Response.Close()
        If InStr(sourcecode, "Username or password is invalid") Then
            MsgBox("Usename or password incorrect")
        Else
            MsgBox("logged in succesfully")
        End If

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim reader As StreamReader

        Dim Request As HttpWebRequest = HttpWebRequest.Create("http://example.com/test/user_settings.php")
        Request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"

        Request.CookieContainer = logincookie
        Dim Response As HttpWebResponse = Request.GetResponse()
        reader = New StreamReader(Response.GetResponseStream())
        Dim theusercp As String = reader.ReadToEnd

        RichTextBox1.Text = theusercp

    End Sub
4

0 回答 0