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
Related
so i am trying to login to a website using httpwebrequest. the post data i got from a http debugger is
code i am trying is:
Dim postData As String = "securitycheck=85b39cc89f04bc1612ce9d0c384b39ca&do_action=log_into_system&jump_to=https%3A%2F%2Fwww.dreamstime.com%2F&uname=jawademail&pass=jawadpass"
Dim tempCookies As New CookieContainer
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.dreamstime.com/securelogin.php"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = tempCookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "https://www.dreamstime.com/login.php"
postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
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
RichTextBox1.Text = thepage
thsi code does not seem to post data in website i get referer page code in richtextbox after running the code.
First GET the page, find the "securitycheck" in its source and extract it.
Combine it with the rest of your data then send it with POST.
Ok so I felt like trying:
Dim LoginData As String
Dim LoginCookies As New CookieContainer() 'Move this outside of sub/function so you can use it later
Dim LoginRequest As HttpWebRequest = WebRequest.Create("https://www.dreamstime.com/login.php")
LoginRequest.CookieContainer = LoginCookies
LoginRequest.KeepAlive = True
LoginRequest.AllowAutoRedirect = True
LoginRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0"
Dim LoginResponse As HttpWebResponse = LoginRequest.GetResponse()
Dim LoginResponseRead As StreamReader = New StreamReader(LoginResponse.GetResponseStream())
Using LoginResponseRead
Do
Dim line As String = LoginResponseRead.ReadLine
If line.Contains("var securitycheck=") Then
LoginData = "securitycheck=" & line.Substring(line.IndexOf("=") + 2, line.LastIndexOf("'") - line.IndexOf("=") - 2)
Exit Do
End If
Loop
End Using
Dim byteData As Byte() = Encoding.UTF8.GetBytes(LoginData)
LoginRequest = WebRequest.Create("https://www.dreamstime.com/securelogin.php")
LoginRequest.CookieContainer = LoginCookies
LoginRequest.Method = "POST"
LoginRequest.KeepAlive = True
LoginRequest.ContentType = "application/x-www-form-urlencoded"
LoginRequest.Referer = "https://www.dreamstime.com/login.php"
LoginRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
LoginRequest.ContentLength = byteData.Length
Dim postreqstream As Stream = LoginRequest.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
LoginResponse = LoginRequest.GetResponse()
LoginResponseRead = New StreamReader(LoginResponse.GetResponseStream())
Dim thepage As String = LoginResponseRead.ReadToEnd
'Now with GET request grab whatever you want, DON'T forget to use cookie.
Result
>>>securitycheck=183d5abdb01f288aacbe5b2893555ec5
Dim email As String = "something"
Dim password As String = "somethingelse"
LoginData &= "&do_action=log_into_system&jump_to=https%3A%2F%2Fwww.dreamstime.com%2F&uname=" & email & "&pass=" & password
>>>securitycheck=183d5abdb01f288aacbe5b2893555ec5&do_action=log_into_system&jump_to=https%3A%2F%2Fwww.dreamstime.com%2F&uname=something&pass=somethingelse
There, practically done.
I took a look at this myself and it appears that with every login request a token is sent that identifies your "session", specifically:
securitycheck=85b39cc89f04bc1612ce9d0c384b39ca
This token changes every time you login, and if it isn't valid the site redirects you back to the login page, asking you to login again.
Sites usually do this to prevent Cross-Site Request Forgery (CSRF). This means that you will most likely not be able to login to this site without using an actual web browser.
Here's the code that was tested and it works. It uses System.Net.Http.HttpClient rather WebClient (since it supports concurrent requests). This code is just a model since its main goal is to show the idea how to work with this site. There are additional explanations in comments. You also need to import System.Web dll.
Imports System.Net.Http
Imports System.Web
Imports System.Text.RegularExpressions
Public Class TestForm
Private Const URL_MAIN$ = "https://www.dreamstime.com"
Private Const URL_LOGIN$ = "https://www.dreamstime.com/securelogin.php"
Private Const URL_LOGOUT$ = "https://www.dreamstime.com/logout.php "
Private Const USER_AGENT$ = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, Like Gecko) " +
"Chrome/68.0.3440.15 Safari/537.36 OPR/55.0.2991.0 " +
"(Edition developer)"
Private Const LOGIN$ = "<USER_NAME>"
Private Const PASS$ = "<USER_PASSWORD>"
Private token$
Private Async Sub OnGo() Handles btnGo.Click
Dim html$
Using client = New HttpClient()
client.DefaultRequestHeaders.Add("User-Agent", USER_AGENT)
Using req = New HttpRequestMessage(HttpMethod.Get, URL_MAIN)
Using resp = Await client.SendAsync(req)
html = Await resp.Content.ReadAsStringAsync()
End Using
End Using
'// Search for security token
Dim m = Regex.Match(
html,
"<input type=""hidden"" name=""securitycheck"" value=""(?'token'\w+)"">")
If Not m.Success Then
MessageBox.Show("Could not find security token.")
Return
End If
'// Get security token
token = m.Groups("token").Value
'// Try to login.
'// For logging to work, we need to use FormUrlEncodedContent class.
'// Also we need to use it every time we do POST requests.
'// No need for it for GET requests (as long as the HttpClient is the same).
Using req = New HttpRequestMessage(HttpMethod.Post, URL_LOGIN) With
{
.Content = GetFormData()
}
Using resp = Await client.SendAsync(req)
html = Await resp.Content.ReadAsStringAsync()
End Using
End Using
'// Go to main page to check we're logged in.
'// "html" variable now MUST contain user's account name.
Using req = New HttpRequestMessage(HttpMethod.Get, URL_MAIN$)
Using resp = Await client.SendAsync(req)
html = Await resp.Content.ReadAsStringAsync()
End Using
End Using
'// Logout.
'// "html" variable now MUST NOT contain user's account name.
Using req = New HttpRequestMessage(HttpMethod.Get, URL_LOGOUT)
Using resp = Await client.SendAsync(req)
html = Await resp.Content.ReadAsStringAsync()
End Using
End Using
End Using
End Sub
Function GetFormData() As FormUrlEncodedContent
Return New FormUrlEncodedContent(New Dictionary(Of String, String) From
{
{"securitycheck", token},
{"do_action", "log_into_system"},
{"jump_to", ""},
{"uname", HttpUtility.HtmlEncode(LOGIN)},
{"pass", HttpUtility.HtmlEncode(PASS)}
})
End Function
End Class
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
I would like to know how will see log into sites like instagram.com, as I have the same question for twitter, my doubt comes when trying to log in by code without the webbrowser using method post in vb.net, trying to use this code returns me on instagram Error 404:
Dim postData As String = "csrfmiddlewaretoken=" & TextBox1.Text & "&username=xxxxx&password=xxxxx"
Dim tempCookies As New CookieContainer
Dim encoding As New ASCIIEncoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://instagram.com/accounts/login/"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = cokkie
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "https://instagram.com/accounts/login/"
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0"
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)
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
RichTextBox1.Text = thepage
I get the csrfmiddlewaretoken the instagram page by method get, really do not understand, but I think I read that I must first get a cookie before log in, but really do not know, if anyone can help me I would greatly appreciate
Are you looking for
http://instagram.com/developer/authentication/
trying to simulate a user logging into the normal web sight seems like hard work, Instagram supports OAuth 2.0 and if you search Nuget for OAuth you will find a whole load of packages to to the work for you.
for reference you can find twitter info at https://dev.twitter.com/docs
Tim
I figured it out, we actually need to send cookies to be able to logging, the code here for those people who have the same question:
Public cokkie As CookieContainer
Public Sub cookie()
'Dim webClient As New System.Net.WebClient
'Dim result As String = webClient.DownloadString("https://instagram.com/accounts/login")
Dim postData As String = ""
Dim tempCookies As New CookieContainer
Dim encoding As New ASCIIEncoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://instagram.com/accounts/login"), HttpWebRequest)
postReq.CookieContainer = tempCookies
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempCookies.Add(postresponse.Cookies)
cokkie = tempCookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
RichTextBox1.Text = thepage
TextBox1.Text = cokkie.ToString
Dim regx As New Regex("name=""csrfmiddlewaretoken"" value=""(.*?)""/>", RegexOptions.IgnoreCase)
Dim mactches As MatchCollection = regx.Matches(thepage)
For Each match As Match In mactches
TextBox1.Text = match.Value
TextBox1.Text = TextBox1.Text.Replace("name=""csrfmiddlewaretoken"" value=""", "")
TextBox1.Text = TextBox1.Text.Replace("""/>", "")
Next
End Sub
Public Sub log()
Dim postData As String = "csrfmiddlewaretoken=" & TextBox1.Text & "&username=xxxx&password=xxxx"
Dim tempCookies As New CookieContainer
Dim encoding As New ASCIIEncoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://instagram.com/accounts/login/"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = cokkie
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "https://instagram.com/accounts/login/"
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0"
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)
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
RichTextBox1.Text = thepage
End Sub
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
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