login with VB.NET and httpwebrequest cookiecontainer - vb.net

I think there is a problem with cookiecontainer (httpwebrequest)
there are 2 main functions in my class, first getting a new form (a hidden token in form tag), and it should set the cookies (which not set) and then second function (doLogin) should login the form. why cookie is not set...?
here is my codes: (you can test my code with "http://wetcatdesign.com/wiki/" as 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

What happens if you set it before res = req.GetResponse() ?

Firstly, you need to set cookies before sending the request and secondly you need to extract cookies from the response when you expect them. Here's one way of doing it
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

Related

Instagram Register HttpWebRegister

I want to make a method to create an Instagram, but I can't to figure out how to get the cookie automatically
My old method :
Function register()
Dim postData As String = "email=" & EmailBox.Text + "#gmail.com" & "&password=" & PassBox.Text & "&username=" & UserBox.Text & "&first_name=" & NameBox.Text
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.instagram.com/accounts/web_create_ajax/"), HttpWebRequest)
request.Method = "POST"
request.KeepAlive = True
request.Headers.Add("X-CSRFToken", "q4NBIiEDDiPwGliNk6xxxxW9IooCHm")
request.ContentType = "application/x-www-form-urlencoded"
request.Headers.Add("X-Instagram-AJAX", "1")
request.Headers.Add("X-Requested-With", "XMLHttpRequest")
request.Headers.Add("Cookie", "mid=WZWf8QALxxxxcWsM-P1hm5F; csrftoken=q4NBIiEDDixxxxZrW9IooCHm; rur=FTW; ig_vw=16; ig_pr=1; ig_vh=4")
request.Referer = "https://www.instagram.com/"
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"
request.ContentLength = byteData.Length
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(byteData, 0, byteData.Length)
requestStream.Close()
Dim responseS As HttpWebResponse
responseS = DirectCast(request.GetResponse(), HttpWebResponse)
Dim Reader As New StreamReader(responseS.GetResponseStream())
Dim thepage As String = Reader.ReadToEnd
If thepage.Contains("This username isn't available. Please try another") Then
Label6.ForeColor = Color.DarkRed
Label6.Text = UserBox.Text + "Has been fail register !!"
Else
Label6.ForeColor = Color.LightGreen
Label6.Text = UserBox.Text + "Has been successfully register !!"
End If
TextBox1.Text = thepage
End Function
How can I get the cookie automatically?
there you go. This is an sample for login in to ASP.NET MVC website. Look for Cookiejar to retreive them.
Dim tclient As HttpClient
Dim cookiejar As New CookieContainer
cookiejar = handler.CookieContainer
Dim xResponse As HttpResponseMessage = Await (tclient.GetAsync(BaseAddress & LoginUrl))
Dim xcookies As CookieCollection = cookiejar.GetCookies(New Uri(BaseAddress & LoginUrl))
For Each tCookie As Cookie In xcookies
If tCookie.Name = "__RequestVerificationToken" Then vCookie = tCookie : VerificationToken = tCookie.Value : Exit For
Next
Dim body As String = Await (xResponse.Content.ReadAsStringAsync())
Dim htdoc As New HtmlAgilityPack.HtmlDocument
htdoc.LoadHtml(body)
Dim xxdoc As HtmlNode = htdoc.GetElementbyId("loginform")
For Each xnodes As HtmlNode In xxdoc.Elements("input")
If xnodes.Attributes(0).Value = "__RequestVerificationToken" Then
FormValidationToken = xnodes.Attributes(2).Value
End If
Next

Can't load a page with httpwebrequest

I want to take the Flight schedule from the following address:
http://fo-apac.ttinteractive.com/Zenith/FrontOffice/(S(nves1yv4xxoia40cmotixof1))/USBangla/en-GB/BookingEngine/SearchFlights?__cnv=tShqK&json={"BookingPathArguments":null,"OriginDestinations":[{"IsOpen":false,"DataIdOrigin":6337,"DataIdDestination":6707,"DateTime":"2016-04-27T00:00:00.000"}],"TravelerTypes":[{"DataId":1,"TravelerCount":1},{"DataId":2,"TravelerCount":0},{"DataId":3,"TravelerCount":0}],"Currency":{"Code":"BDT"},"PromoCode":null,"DisplayRealAvailability":false,"Visibility":0,"ExtendedSearchDayCount":3}
If you paste the address to browser address bar and use firebug (or any fiddler), you will see this page sends 3 jquery ajax calls to bring the schedule. The following ajax POST actually fetch the schedule.
http://fo-apac.ttinteractive.com/Zenith/FrontOffice/(S(nves1yv4xxoia40cmotixof1))/USBangla/en-GB/FlexibleFlightStaticAjax/FlexibleFlightListLoadSelectedDays?__cnv=mxw0s
PostData : SaleConditionAccepted=false&ExtendedSearchDayCount=3&DoNotCheckCache=false&AlreadyLoggedIn=false&TempDataGuid=nves1yv4xxoia40cmotixof1&CurrencyCode=BDT&FareBasisDataId=&Travelers[0][DataId]=1&Travelers[0][Count]=1&UserSelections[0][SelectedDate]=2016-04-27T00:00:00&UserSelections[0][ReferenceDate]=2016-04-27T00:00:00&UserSelections[0][DataIdOrigin]=6337&UserSelections[0][DataIdDestination]=6707&UserSelections[0][GenericClassDataId]=&UserSelections[0][SelectedSegments]=&JsonPrepareBookingRequest=&PromoCode=
I am sending the request with httpwebrequest, but for unknown reason, I miss the session. I used CookieContainer to keep the cookies. I used the following function to send httprequest:
Public Function GetPostWP(ByVal Url As String, ByVal CkCont As CookieContainer, Optional ByVal PostData As String = "", Optional ByVal refSite As String = "") As String
Dim pStr As String = ""
Try
Dim Http As HttpWebRequest = WebRequest.Create(Url)
If refSite <> "" Then Http.Referer = refSite
Http.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate")
Http.CookieContainer = CkCont 'Initial CkCont is Nothing
Http.KeepAlive = True
Http.AllowAutoRedirect = True
'Http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6"
Http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Http.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36"
If PostData <> "" Then
Http.Method = "POST"
Http.ContentLength = PostData.Length
Http.ContentType = "application/x-www-form-urlencoded"
Dim PostStream As StreamWriter = New StreamWriter(Http.GetRequestStream())
PostStream.Write(PostData)
PostStream.Close()
End If
Using WebResponse As HttpWebResponse = Http.GetResponse()
Dim responseStream As Stream = WebResponse.GetResponseStream()
If (WebResponse.ContentEncoding.ToLower().Contains("gzip")) Then
responseStream = New GZipStream(responseStream, CompressionMode.Decompress)
ElseIf (WebResponse.ContentEncoding.ToLower().Contains("deflate")) Then
responseStream = New DeflateStream(responseStream, CompressionMode.Decompress)
End If
Dim reader As StreamReader = New StreamReader(responseStream, Encoding.Default)
pStr = reader.ReadToEnd()
responseStream.Close()
End Using
tmpCky = CkCont 'tmpCky is a Public CookieContainer Variable to hold cookies for future use.
GetPostWP = pStr
Catch ex As Exception
GetPostWP = "Error : " & ex.Message
End Try
End Function
Dim Cky As New CookieContainer
Dim Txt as String = GetPostWP(PostAddress, Cky, PostData, RefAdd)
Cky = tmpCky
Can anyone analyze the page, please?

Wordpress HttpWebrequest vb.net

I am trying to code some self bot to do some stuff for me on my self hosted wordpress blogs, so I managed to login successfully using webrequests had some problems but solved them.
But now I'm trying to go to permalinks page for example to get some data but when Im trying to do it using the login cookie it just redirects me back to login page like I'm not using the login cookie.
So basically this is the login function:
cleanurl = TextBox3.Text
logincookie = New CookieContainer
Dim url As String = cleanurl & "/wp-login.php"
Dim postreq As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
Dim cookies As New CookieContainer
postreq.CookieContainer = cookies
postreq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b6pre) Gecko/20100903 Firefox/4.0b6pre"
postreq.KeepAlive = True
postreq.Timeout = 120000
postreq.Method = "POST"
postreq.Referer = url
postreq.AllowAutoRedirect = False
postreq.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = "log=" & TextBox1.Text & "&pwd=" & TextBox2.Text & "&wp-submit=Log+In&redirect_to=" & cleanurl & "/wp-admin" & "&testcookie=1"
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
postreq.ContentLength = byteData.Length
Dim postreqstream As Stream = postreq.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postreq.GetResponse, HttpWebResponse)
'/ The Following is set next request with authentication cookie
Dim nextreq As HttpWebRequest = DirectCast(HttpWebRequest.Create(cleanurl), HttpWebRequest)
nextreq.ContentType = "application/x-www-form-urlencoded"
nextreq.Method = "GET"
nextreq.CookieContainer = New CookieContainer
nextreq.CookieContainer.Add(postresponse.Cookies)
nextreq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b6pre) Gecko/20100903 Firefox/4.0b6pre"
nextreq.KeepAlive = True
Dim nextresponse As HttpWebResponse
nextresponse = DirectCast(nextreq.GetResponse, HttpWebResponse)
logincookie = nextreq.CookieContainer
logincookie.Add(nextresponse.Cookies)
Dim postreqreader As New StreamReader(nextresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
nextresponse.Close()
RichTextBox1.Text = thepage
WebBrowser1.DocumentText = thepage
Refresh()
If thepage.Contains("ERROR") Then
MsgBox("Error logging in!")
Else
MsgBox("Lets Start Blogging!")
End If
It works perfect, gets me to the URL homepage and shows me that Im logged in.
but when Im launching this code to get to the permalinks edit page it just returns the login page source code means it wasn't able to login.
Dim nextreq As HttpWebRequest = DirectCast(HttpWebRequest.Create(cleanurl & "/wp-admin/options-permalink.php"), HttpWebRequest)
nextreq.ContentType = "application/x-www-form-urlencoded"
nextreq.Method = "GET"
nextreq.CookieContainer = logincookie
nextreq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b6pre) Gecko/20100903 Firefox/4.0b6pre"
nextreq.KeepAlive = True
Dim nextresponse As HttpWebResponse = DirectCast(nextreq.GetResponse, HttpWebResponse)
nextreq.CookieContainer.Add(nextresponse.Cookies)
Dim postreqreader As New StreamReader(nextresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
nextresponse.Close()
RichTextBox1.Text = thepage
WebBrowser1.DocumentText = thepage
Refresh()
Here is an alternative. Try the Wordpress API (xmlrpc.php) to access and modify data in your Wordpress installation. I have used CookComputing.XmlRpc to achieve this.
Here is a sample on how to create a new WordPress post:
Imports CookComputing.XmlRpc
Public Sub Add_New_Post_Sample()
Dim NewPostContent As New NewPostContent
NewPostContent.post_type = "post"
NewPostContent.post_status = "draft"
NewPostContent.post_title = "MyTitle"
NewPostContent.post_author = "1"
NewPostContent.post_excerpt = ""
NewPostContent.post_content = "MyContent"
NewPostContent.post_date_gmt = "2015-01-21 00:00:00"
NewPostContent.post_name = "my-unique-url"
NewPostContent.post_password = ""
NewPostContent.comment_status = "closed"
NewPostContent.ping_status = "closed"
NewPostContent.sticky = False
NewPostContent.post_thumbnail = 0
NewPostContent.post_parent = 0
NewPostContent.Mycustom_fields = New String() {""}
Dim API = DirectCast(XmlRpcProxyGen.Create(GetType(IgetCatList)), IgetCatList)
Dim clientprotocal = DirectCast(API, XmlRpcClientProtocol)
clientprotocal.Url = "http://myurl.com/xmlrpc.php"
Dim result As String = API.NewPost(1, "admin", "password", NewPostContent)
Console.WriteLine(result)
End Sub
Public Structure NewPostContent
Public post_type As String
Public post_status As String
Public post_title As String
Public post_author As Integer
Public post_excerpt As String
Public post_content As String
Public post_date_gmt As DateTime
Public post_name As String
Public post_password As String
Public comment_status As String
Public ping_status As String
Public sticky As Boolean
Public post_thumbnail As Integer
Public post_parent As Integer
Public Mycustom_fields As String()
End Structure

vb.net httpwebrequest to login to EmpireAvenue.com

This is driving me insane. I know I have to be close on this. My requests matches a real one as far as I can see except the cookies are a bit different. I appear to be missing the google analytics ones. Not sure if that is the issue or not. I get redirected like I am supposed to but on the redirect page it is asking me to login again. Any help is appreciated. Here is my code:
Private Function eaLogin(ByVal ticker As String, ByVal password As String)
Try
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = httpWebRequest.Create("http://www.empireavenue.com")
request.Credentials = CredentialCache.DefaultCredentials
request.CookieContainer = cookieJar
Dim response As HttpWebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Dim session As String = ""
ServicePointManager.Expect100Continue = False
'Set the initial parameters
Dim UserID As String = ticker ' Username
Dim PWord As String = HttpUtility.UrlEncode(password) ' Password
Dim domain As String = "https://www.empireavenue.com/user/login/do"
Dim encoding As New System.Text.ASCIIEncoding
' Use the appropriate HTML field names to stuff into the post header
Dim PostData As String = _
"login_username=" & ticker & _
"&login_password=" & PWord
Dim Data() As Byte = encoding.GetBytes(PostData)
' Initialise the request
Dim LoginReq As Net.HttpWebRequest = Net.WebRequest.Create(domain) ' Login location taken from the form action
With LoginReq
.KeepAlive = True
.Method = "POST"
' Note: if the page uses a redirect if will fail
.AllowAutoRedirect = False
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = Data.Length
' Set empty container
.CookieContainer = cookieJar
.Referer = "http://www.empireavenue.com/"
.UserAgent = userAgent
.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.Host = "www.empireavenue.com"
End With
' Add the POST data
Dim SendReq As IO.Stream = LoginReq.GetRequestStream
LoginReq.Headers.Add("Accept-Language", "en-US,en;q=0.5")
LoginReq.Headers.Add("Accept-Encoding", "gzip, deflate")
SendReq.Write(Data, 0, Data.Length)
SendReq.Close()
' Obtain the response
Dim LoginRes As Net.HttpWebResponse = LoginReq.GetResponse()
' Retreive the headers from the request (e.g. the location header)
Dim Redirect As String = LoginRes.Headers("Location")
' Add any returned cookies to the cookie collection
cookieJar.Add(LoginRes.Cookies)
' Move to the redirected page as a GET request...
Dim newUrl As String = ""
If Not (Redirect Is Nothing) Then
If Redirect.StartsWith("http://") Then
newUrl = Redirect
Else
newUrl = "https://www.empireavenue.com" & Redirect
End If
LoginReq = Net.WebRequest.Create(newUrl)
With LoginReq
.KeepAlive = False
.Method = "GET"
.ContentType = "application/x-www-form-urlencoded"
.AllowAutoRedirect = True
.CookieContainer = cookieJar
End With
' Perform the navigate and output the HTML
LoginRes = LoginReq.GetResponse()
Dim sReader As IO.StreamReader = New IO.StreamReader(LoginRes.GetResponseStream)
Dim HTML As String = sReader.ReadToEnd
If HTML.Contains(ticker) Then
MessageBox.Show("yay!")
Return True
Else
MessageBox.Show("no!")
Return False
End If
Else
MessageBox.Show("no too!")
Return False
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
Return False
End Try
End Function
I couldn't try it on the empirevenue because of the restrictions at work but try this:
Dim tempCookies As CookieContainer
ServicePointManager.Expect100Continue = False
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.empireavenue.com/user/login/do"), HttpWebRequest)
Dim postData As String = "login_username=" & ticker & "&login_password=" & PWord
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = tempCookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "http://www.empireavenue.com/"
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1"
postReq.ContentLength = byteData.Length
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempCookies.Add(postresponse.Cookies)
logincookie = tempCookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
Hope it will work for you

VB.Net HTTPWebRequest Login 403 Error

I'm attempting to login to a website ("https://instagram.com/") through web requests in VB.Net. My credentials are correct and I am grabbing the required token correctly, however I am returned a 403 HTTP error when logging in. My current code, including my POST/GET functions, can be found below.
POST_ERROR: The remote server returned an error: (403) Forbidden.
Code:
Imports System.Net
Imports System.IO
Imports System.Text
Module Main
Dim Token$ = ""
Dim myCookie As New CookieContainer
Private Sub UpdateToken(ByVal Page$)
Token = GetBetween(Page, "csrfmiddlewaretoken" & Chr(34) & " value=" & Chr(34), Chr(34) & "/>")
End Sub
Private Function GETreq(ByVal URL$)
Try
Dim tempCookie As New CookieContainer
Dim Request As HttpWebRequest = TryCast(WebRequest.Create(URL), HttpWebRequest)
Request.Method = "GET"
Request.CookieContainer = myCookie
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0"
Request.KeepAlive = True
Dim Response As HttpWebResponse = Request.GetResponse()
Dim ResponseStream As Stream = Response.GetResponseStream()
Dim StreamReader As New StreamReader(ResponseStream)
Dim Text$ = StreamReader.ReadToEnd()
tempCookie.Add(Response.Cookies)
myCookie = tempCookie
Return Text
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("GET_ERROR: " & ex.Message)
Return ""
End Try
End Function
Private Function POSTreq(ByVal URL$, ByVal Data$)
Try
Dim tempCookie As New CookieContainer
Dim DataBytes As Byte() = Encoding.ASCII.GetBytes(Data)
Dim Request As HttpWebRequest = TryCast(WebRequest.Create(URL), HttpWebRequest)
Request.Method = "POST"
Request.ContentType = "application/x-www-form-urlencoded"
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0"
Request.ContentLength = DataBytes.Length
Request.CookieContainer = myCookie
Request.KeepAlive = True
Dim PostData As Stream = Request.GetRequestStream()
PostData.Write(DataBytes, 0, DataBytes.Length)
PostData.Close()
Dim Response As HttpWebResponse = Request.GetResponse()
Dim ResponseStream As Stream = Response.GetResponseStream()
Dim StreamReader As New StreamReader(ResponseStream)
Dim Text$ = StreamReader.ReadToEnd()
tempCookie.Add(Response.Cookies)
myCookie = tempCookie
Return Text
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("POST_ERROR: " & ex.Message)
Return ""
End Try
End Function
Public Function GetBetween(ByRef strSource$, ByRef strStart$, ByRef strEnd$, Optional ByRef startPos As Integer = 0) As String
Try
Dim iPos As Integer, iEnd As Integer, lenStart As Integer = strStart.Length
Dim strResult$
strResult = String.Empty
iPos = strSource.IndexOf(strStart, startPos)
iEnd = strSource.IndexOf(strEnd, iPos + lenStart)
If iPos <> -1 AndAlso iEnd <> -1 Then
strResult = strSource.Substring(iPos + lenStart, iEnd - (iPos + lenStart))
End If
Return strResult
Catch ex As Exception
Return ""
End Try
End Function
Sub Main()
Dim Username$ = "XXX"
Dim Password$ = "XXX"
UpdateToken(GETreq("https://instagram.com/accounts/login/"))
UpdateToken(POSTreq("https://instagram.com/accounts/login/", String.Format("csrfmiddlewaretoken={0}&username={1}&password={2}", Token, Username, Password)))
Console.ReadLine()
End Sub
End Module