POST + cookie 的示例代码?

问题描述 投票:0回答:1

我一直在谷歌上搜索一些 VB.Net 代码,以使用 POST 方法对 Web 服务器进行身份验证,在 cookie 中接收会话 ID,然后将此 cookie 与所有 GET 查询一起发送......但我发现的只是一半- 工作代码或 C# 代码,即。对于 VB.Net 新手来说很难使用。

有人有一些方便的代码或一些我可以用来入门的指针吗?

谢谢你。

vb.net http cookies post
1个回答
0
投票

对于那些有兴趣进行屏幕抓取的人,这里有一些工作代码,用于发布登录名/密码、在 cookie 中获取会话 ID 以及从站点获取其他页面:

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

Public Class Form1
    Const ConnectURL = "http://www.acme.com/logon.php"
    Const HomeURL = "http://www.acme.com"

    Private Function RegularPage(ByVal URL As String, ByVal CookieJar As CookieContainer) As String
        Dim reader As StreamReader

        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.AllowAutoRedirect = False
        Request.CookieContainer = CookieJar

        Dim Response As HttpWebResponse = Request.GetResponse()

        reader = New StreamReader(Response.GetResponseStream())
        Return reader.ReadToEnd()
        Response.Close()
    End Function

    Private Sub LogonPage(ByVal URL As String, ByRef CookieJar As CookieContainer, ByVal PostData As String)
        Dim reader As StreamReader

        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 = CookieJar
        Request.AllowAutoRedirect = False
        Request.ContentType = "application/x-www-form-urlencoded"
        PostData = "username=isiria&password=ceciestunmdp"
        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()

        For Each tempCookie In Response.Cookies
            CookieJar.Add(tempCookie)
        Next

        reader = New StreamReader(Response.GetResponseStream())
        Response.Close()
    End Sub

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

        Try
            'Logon
            PostData = "username=jdoe&password=test"
            LogonPage(ConnectURL, CookieJar, PostData)

            'Homepage
            RichTextBox1.AppendText(RegularPage(HomeURL, CookieJar))
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub
End Class
© www.soinside.com 2019 - 2024. All rights reserved.