我覺得這是與的CookieContainer(HttpWebRequest的)登錄用VB.NET和HttpWebRequest的的CookieContainer
有我的2個主要功能,首先獲得一個新的形式(隱藏令牌形式的標籤)的問題,並它應該設置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
哦!是!我意外地犯了這個錯誤,但即使我糾正後也不會工作...... –
我找到了解決方案:req.Headers.Set(「Cookie」,CookieJar)'設置Cookie res = req.GetResponse() CookieJar = res.Headers.Get(「Set-Cookie」)'獲取cookies –