What I'm trying to do is pass credentials to a website to log into it. I'm able to get an authenticity token and also POST a token with login information. Unfortunately, my code for getting the token via HttpWebResponse gets a token in one stream and closes, so that token is different than the new token required in my HttpWebRequest stream. What I need to do is utilize HttpWebRequest to get a token, not close the stream, then POST data. I have yet to see an example on search engines that matches this criteria.
I got this from a forum. It grabs the token string:
Expand|Select|Wrap|Line Numbers
- Private Function getToken()
- Dim r As HttpWebRequest = HttpWebRequest.Create("https://n135.meraki.com")
- Dim re As HttpWebResponse = r.GetResponse()
- Dim src As String = New StreamReader(re.GetResponseStream()).ReadToEnd()
- Return (GetBetween(src, "<input name=""authenticity_token"" type=""hidden"" value=""", """ /></div> "))
- End Function
Expand|Select|Wrap|Line Numbers
- Private Function GetBetween(ByVal Source As String, ByVal Str1 As String, ByVal Str2 As String, Optional ByVal Index As Integer = 0) As String
- Return (Regex.Split(Regex.Split(Source, Str1)(Index + 1), Str2)(0))
- End Function
Expand|Select|Wrap|Line Numbers
- Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
- Dim token As String = getToken()
- Dim postData As String = "" 'formatted token string with username and password goes here
- Dim tempCookies As New CookieContainer
- Dim encoding As New UTF8Encoding
- Dim byteData As Byte() = encoding.GetBytes(postData)
- Dim r As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://n135.meraki.com"), HttpWebRequest)
- r.KeepAlive = True
- r.Method = "POST"
- r.CookieContainer = tempCookies
- r.ContentType = "application/x-www-form-urlencoded"
- r.Referer = "https://n135.meraki.com"
- r.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36"
- r.ContentLength = byteData.Length
- Dim re As Stream = r.GetRequestStream()
- re.Write(byteData, 0, byteData.Length)
- re.Close()
- Dim res As HttpWebResponse = DirectCast(r.GetResponse(), HttpWebResponse)
- tempCookies.Add(res.Cookies)
- loginCookies = tempCookies
- Dim src As String = New StreamReader(res.GetResponseStream()).ReadToEnd()
- If (src.Contains("Welcome")) Then
- loginCookies = tempCookies
- MsgBox("Success!")
- Else
- tempCookies = Nothing
- MsgBox("Failed.")
- End If
- End Sub