使用VB.NET和httpwebrequest cookiecontainer登录

时间:2012-05-30 16:46:46

标签: vb.net cookies httpwebrequest cookiecontainer

我认为cookiecontainer(httpwebrequest)存在问题

我的课程中有两个主要功能,首先是获取一个新表单(表单标签中的隐藏标记),它应该设置cookie(未设置),然后第二个函数(doLogin)应该登录表单。为什么没有设置cookie ...? 这是我的代码:(您可以使用“http://wetcatdesign.com/wiki/”作为wikiURL测试我的代码)

Public Class wiki_submitter
Dim CookieJar As New CookieContainer
Public wikiURL As String

Private Function cutStr(ByVal Str As String, ByVal startStr As String, _
                        ByVal finishStr As String, Optional ByVal startPos As Integer = 1) As String
    Dim start As Integer = InStr(startPos, Str, startStr) + Len(startStr)
    Dim finish As Integer = InStr(start + 1, Str, finishStr)
    cutStr = Mid(Str, start, finish - start)
End Function

Public Function GetNewForm()
    Try
        Dim req As HttpWebRequest = HttpWebRequest.Create(wikiURL & "index.php?title=Special:UserLogin&returnto=Main_Page")
        Dim res As HttpWebResponse
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"
        res = req.GetResponse()
        'Setting cookies
        req.CookieContainer = CookieJar

        'getting HTML result
        Dim sr As StreamReader = New StreamReader(res.GetResponseStream())
        Dim HTML = sr.ReadToEnd
        sr.Close()


        Dim wpLoginToken As String = cutStr(HTML, "<input type=""hidden"" name=""wpLoginToken"" value=""", """") ' finding wpLoginToken parameter
        GetNewForm = wpLoginToken
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Function

Public Function doLogin(ByVal username As String, ByVal pass As String)
    Dim req As HttpWebRequest = HttpWebRequest.Create(wikiURL & "index.php?title=Special:UserLogin&action=submitlogin&type=login")
    Dim res As HttpWebResponse
    Dim HTML As String
    '-------Setting up headers------------
    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"
    req.Referer = wikiURL & "index.php?title=Special:UserLogin&returnto=Main_Page"
    req.ContentType = "application/x-www-form-urlencoded" 'Form content type
    req.Method = "POST" 'data will be send in POST method
    req.CookieContainer = CookieJar 'Setting cookies
    '-------------------------------------

    Dim sw As StreamWriter = New StreamWriter(req.GetRequestStream)
    Dim poststring = "wpLoginToken=" & GetNewForm() & "&wpLoginattempt=Log in&wpName=" & username & "&wpPassword=" & pass
    Try
        sw.Write(poststring)
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        sw.Close()
    End Try

    res = req.GetResponse()
    Dim sr As StreamReader = New StreamReader(res.GetResponseStream())
    HTML = sr.ReadToEnd 'HTML as result
    sr.Close()

    doLogin = HTML 'returns HTML result
End Function
End Class

2 个答案:

答案 0 :(得分:0)

如果您在res = req.GetResponse()之前设置了该怎么办?

答案 1 :(得分:0)

首先,您需要在发送请求之前设置Cookie,其次,您需要在预期时从响应中提取Cookie。这是一种做法

Public Class wiki_submitter
    Dim CookieJar As New CookieContainer
    Public wikiURL As String

    Private Function cutStr(ByVal Str As String, ByVal startStr As String, _
                            ByVal finishStr As String, Optional ByVal startPos As Integer = 1) As String
        Dim start As Integer = InStr(startPos, Str, startStr) + Len(startStr)
        Dim finish As Integer = InStr(start + 1, Str, finishStr)
        cutStr = Mid(Str, start, finish - start)
    End Function

    Public Function GetNewForm()
        Try
            Dim req As HttpWebRequest = HttpWebRequest.Create(wikiURL & "index.php?title=Special:UserLogin&returnto=Main_Page")
            Dim res As HttpWebResponse
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"
            res = req.GetResponse()
            'Setting cookies
            'req.CookieContainer = CookieJar
            SaveIncomingCookies(res, wikiURL)

            'getting HTML result
            Dim sr As StreamReader = New StreamReader(res.GetResponseStream())
            Dim HTML = sr.ReadToEnd
            sr.Close()


            Dim wpLoginToken As String = cutStr(HTML, "<input type=""hidden"" name=""wpLoginToken"" value=""", """") ' finding wpLoginToken parameter
            GetNewForm = wpLoginToken
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Function

    Public Function doLogin(ByVal username As String, ByVal pass As String)
        Dim req As HttpWebRequest = HttpWebRequest.Create(wikiURL & "index.php?title=Special:UserLogin&action=submitlogin&type=login")
        Dim res As HttpWebResponse
        Dim HTML As String
        '-------Setting up headers------------
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"
        req.Referer = wikiURL & "index.php?title=Special:UserLogin&returnto=Main_Page"
        req.ContentType = "application/x-www-form-urlencoded" 'Form content type
        req.Method = "POST" 'data will be send in POST method
        'req.CookieContainer = CookieJar 'Setting cookies
        '-------------------------------------

        Dim sw As StreamWriter = New StreamWriter(req.GetRequestStream)
        Dim poststring = "wpLoginToken=" & GetNewForm() & "&wpLoginattempt=Log in&wpName=" & username & "&wpPassword=" & pass
        Try
            req.CookieContainer = CookieJar
            sw.Write(poststring)
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            sw.Close()
        End Try

        res = req.GetResponse()
        SaveIncomingCookies(res, wikiURL)
        Dim sr As StreamReader = New StreamReader(res.GetResponseStream())
        HTML = sr.ReadToEnd 'HTML as result
        sr.Close()

        doLogin = HTML 'returns HTML result
    End Function

    Private Function SaveIncomingCookies(ByRef response As HttpWebResponse, ByRef Uri As String)


        If response.Headers("Set-Cookie") <> Nothing Then
            CookieJar.SetCookies(New Uri("http://wetcatdesign.com"), response.Headers("Set-Cookie"))
        End If

    End Function
End Class