vb.net httpwebrequest to login to EmpireAvenue.com - vb.net

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

Related

Cache Issue on HttpWebRequest vb.net

I need away to disable chaching for my VB.NET code. I've found some hints in C#, but nothing that I can get to work.
Right now, when i send in a request, i'm getting the previous request results.
Here's my code:
Dim responseData As String = ""
Try
Dim cookieJar As New Net.CookieContainer()
Dim hwrequest As Net.HttpWebRequest = Net.WebRequest.Create(URL)
hwrequest.CookieContainer = cookieJar
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
'hwrequest.CachePolicy = CachePolicy
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader =
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
cookieJar = Nothing
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function```
Any help would be appreciated!

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

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 and Facebook Photo Upload -- Getting 400 Bad Request

Holy wow I've tried everything from writing my own headers to converting C# examples and I still can't get past the 400 Bad Request error when uploading a photo.
I have every possible permission added and my token is correct.
I can post status updates to my feed, I just can't get images uploaded. Here are two different approaches I tried, and both give me 400 Bad Request...
1
Dim myReq As HttpWebRequest
Dim myRes As HttpWebResponse
Dim encoding As New System.Text.ASCIIEncoding()
Dim postData As String
Dim data() As Byte
Dim sr As StreamReader
Dim imagedata As String
imagedata = File.OpenText("C:\ebay00042-1.jpg").ReadToEnd()
postData += "access_token=MY_TOKEN_HERE_29ZB51pPizthxX5lhmst3MZC7hYXQhW8ZB8e7sVVLzEaN8ZCZAzAgrzk1pisw3ZCtK5lwMMTZBUhe07xTsQvfeHosA1GFUAZDZD&message=this is a test123&source=" & imagedata 'File.ReadAllBytes(photoPath)
data = encoding.GetBytes(postData)
myReq = WebRequest.Create("https://graph.facebook.com/380406275386560/photos")
DirectCast(myReq, System.Net.HttpWebRequest).UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"
myReq.Method = "POST"
myReq.ContentType = "application/x-www-form-urlencoded"
myReq.ContentLength = data.Length
Dim myStream As Stream = myReq.GetRequestStream
myStream.Write(data, 0, data.Length)
myStream.Close()
myRes = myReq.GetResponse
sr = New StreamReader(myRes.GetResponseStream)
Dim strHTML As String = sr.ReadToEnd
2, trying to create my own headers..
Dim myReq As HttpWebRequest
Dim myRes As HttpWebResponse
Dim encoding As New System.Text.ASCIIEncoding()
Dim data() As Byte
Dim sr As StreamReader
Dim boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("----------").Append(boundary).Append("\r\n")
sb.Append("Content-Disposition: form-data; name=""access_token""").Append("\r\n")
sb.Append("\r\n")
sb.Append("MY_TOKEN_HERE_MZC7hYXQhW8ZB8e7sVVLzEaN8ZCZAzAgrzk1pisw3ZCtK5lwMMTZBUhe07xTsQvfeHosA1GFUAZDZD").Append("\r\n")
sb.Append("----------").Append(boundary).Append("\r\n")
sb.Append("Content-Disposition: form-data; name=""message""").Append("\r\n")
sb.Append("\r\n")
sb.Append("Testttt").Append("\r\n")
sb.Append("----------").Append(boundary)
sb.Append("Content-Disposition: file; name=""source"" filename=""ebay00042-1.jpg""").Append("\r\n")
sb.Append("Content-Type: image/jpeg).Append(\r\n")
'sb.Append("Content-Transfer-Encoding: binary").Append("\r\n")
sb.Append("\r\n")
sb.Append(File.OpenText("C:\ebay00042-1.jpg").ReadToEnd()).Append("\r\n")
sb.Append("----------").Append(boundary).Append("----------").Append("\r\n")
'txtCaption.Text = sb.ToString
data = encoding.GetBytes(sb.ToString)
myReq = WebRequest.Create("https://graph.facebook.com/380406275386560/photos")
DirectCast(myReq, System.Net.HttpWebRequest).UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"
myReq.Method = "POST"
myReq.ContentType = "multipart/form-data; boundary=" + boundary
'myReq.ContentType = "application/x-www-form-urlencoded"
myReq.ContentLength = data.Length
Dim myStream As Stream = myReq.GetRequestStream
myStream.Write(data, 0, data.Length)
myStream.Close()
myRes = myReq.GetResponse
sr = New StreamReader(myRes.GetResponseStream)
Dim strHTML As String = sr.ReadToEnd
Any help would be greatly appreciated!
I don't know anything about Facebook's API, but if I were you I'd have a good look at http://csharpsdk.org/
If I had to send an image based on the info you provided, it would look something like this :
' Request URL, image file to send, token and result HTML buffer
Dim reqUrl As String = "https://graph.facebook.com/380406275386560/photos"
Dim imageData As Byte() = File.ReadAllBytes("C:\ebay00042-1.jpg")
Dim token As String = "MY_TOKEN_HERE"
Dim strHtml As String = ""
' Request
Dim request As WebRequest = WebRequest.Create(reqUrl)
request.Headers.Add("access_token", token)
request.Method = "POST"
' set *correct* content type
request.ContentType = "image/jpeg"
' write image data to request stream
Using str = request.GetRequestStream()
str.Write(imageData, 0, imageData.Length)
End Using
' response
Dim response As WebResponse = request.GetResponse()
' HTTP Status
Dim status As Integer = CType(response, HttpWebResponse).StatusCode
If status = 200 Then
' success
Using reader As New StreamReader(response.GetResponseStream())
strHtml = reader.ReadToEnd()
End Using
Else
' oops
End If
Hope that helps.

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