vb.net Post login data httpwebrequest and cookies - vb.net

im currently trying to login to my website, this works however it wont redirect when it logs in. here is my code
Dim request As WebRequest = WebRequest.Create("http://www.jamiehayles.com/test/login.php")
request.Method = "POST"
Dim postData As String = "username=testing&password=lmao1234"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
RichTextBox1.Text = responseFromServer
reader.Close()
dataStream.Close()
response.Close()
my question is, do i need cookies for it to redirect? and if so any help guys?

Take a look at what you're doing with the response from the server:
Dim responseFromServer As String = reader.ReadToEnd()
RichTextBox1.Text = responseFromServer
All you're doing is reading it and placing the content of the response into a text box. You're not actually responding to a redirect in any way.
A "redirect" means that the server responds with a specific status code and header in the response. The status code tells the browser that the response is an instruction to redirect to another resource. The header contains the new resource that the browser should request.
A web browser checks the response for this code/header and performs a new request. Your code doesn't. It just shows the response to the user, regardless of what it is.
So, to illustrate, a normal redirect happens like this:
Browser: I'm requesting this resource.
Server: Ok, I've received your request, but the resource you really want is actually over there.
Browser: Ok, then I'm now requesting that resource over there.
Server: Ok, here you go.
Your code, however, is more like this:
Code: I'm requesting this resource.
Server: Ok, I've received your request, but the resource you really want is actually over there.
Code: [no further action is taken]
The server instructed your code, in an HTTP-standard way, to request a new resource. Your code simply ignored that instruction.
You need to check the status code of the response, as well as the headers of the response, and make new requests accordingly.

Related

Can't make BigCommerce API call in VB.NET

I get
'underlying connection was closed'
when running the code below. I am using vb.net 2012 (I must use this version) with the RestSharp library and am trying to retrieve product data from a bigcommerce.com store. This is a simple vb.net 2012 console program that once I get working I can build upon. I have tried changing around the code somewhat even making certain things redundant like the method and URL but I can't get it to work.
Dim client As New RestClient
client.BaseUrl = New Uri("https://api.bigcommerce.com/stores/mystorehash/v3/catalog/products")
Dim request As New RestRequest("https://api.bigcommerce.com/stores/mystorehash/v3/catalog/products", Method.GET)
request.AddHeader("Accept", "application/json")
request.AddHeader("Content-Type", "application/json")
request.AddHeader("X-Auth-Client", "notactualvaluenotactualvalue")
request.AddHeader("X-Auth-Token", "notactualvaluenotactualvalue")
request.Method = Method.GET
Dim response As New RestResponse
response = client.ExecuteAsGet(request, Method.GET)
Console.WriteLine("response.Content=" & response.Content)
Console.WriteLine("response.ErrorMessage=" & response.ErrorMessage)
Console.WriteLine("response.ResponseStatus=" & response.ResponseStatus)
Console.WriteLine("response.IsSuccessful=" & response.IsSuccessful)
Console.WriteLine("response.Headers.Count=" & response.Headers.Count)
Output:
Any help would be appreciated, hopefully I'm doing something stupid that can be easily fixed
For anyone else that finds this the full implementation of Nathan Booker's suggestion is below. When you attempt to access the Big Commerce api in a VB.NET application you need to specify TLS 1.2. If you don't you'll recieve an HTTP status of 502 - System.IO.IOException Authentication failed because the remote party has closed the transport stream. The solve is done like:
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
ServicePointManager.DefaultConnectionLimit = 9999
Dim request As HttpWebRequest = CType(WebRequest.Create("https://api.bigcommerce.com/stores/<Redacted>/v3/catalog/products"), HttpWebRequest)
request.AllowAutoRedirect = True
request.ContentType = "application/json"
request.Accept = "application/json"
request.Method = "GET"
request.Headers.Add("X-Auth-Client", "<Redacted>")
request.Headers.Add("X-Auth-Token", "<Redacted>")
Dim response As WebResponse = request.GetResponse()
Diagnostics.Debug.WriteLine((CType(response, HttpWebResponse)).StatusDescription)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Diagnostics.Debug.WriteLine(responseFromServer)
reader.Close()
response.Close()
This may be related to your HTTP version or (more likely) SSL/TLS protocol.
If possible, please make sure you're using HTTP 1.1 and TLS 1.2.

Reading from API using VB.NET

I was hoping someone could tell me how to structure a HttpWebRequest in VB.NET to be able to retrieve information using the following API: https://api.developer.lifx.com/docs/list-lights
The code I am interested in replicating is here (in Python):
import requests
token = "YOUR_APP_TOKEN"
headers = {
"Authorization": "Bearer %s" % token,
}
response = requests.get('https://api.lifx.com/v1/lights/all', headers=headers)
A cURL version of this can be seen here:
curl "https://api.lifx.com/v1/lights/all" \
-H "Authorization: Bearer YOUR_APP_TOKEN"
My question is: how do I do this in VB.NET? Would a HttpWebRequest be the way to go? If so, could you please assist me by providing some example code?
I am hoping to retrieve a list of all my lights.
That is correct; A HTTP Request would be the way to go. The python sample code you provided mentions headers which can also be done using a WebHeaderCollection. One other way to do it is using a web client.
Web client (No headers)
Dim client As New WebClient
Dim data As String = client.DownloadString("https://api.lifx.com/v1/lights/all")
With Headers using WebRequest
'String for token
Dim tokenString As String = "YOUR_APP_TOKEN"
'Stream for the responce
Dim responseStream As System.IO.Stream
'Stream reader to read the stream to a string
Dim stringStreamReader As System.IO.StreamReader
'String to be read to
Dim responseString As String
'The webrequest that is querying
Dim webRequest As WebRequest = WebRequest.Create("https://api.lifx.com/v1/lights/all")
'The collection of headers
Dim webHeaderCollection As WebHeaderCollection = webRequest.Headers
'Adding a header
webHeaderCollection.Add("Authorization:Bearer " + tokenString)
'The web responce
Dim webResponce As HttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
'Reading the web responce to a stream
responseStream = webResponce.GetResponseStream()
'Initializing the stream reader with our stream
stringStreamReader = New StreamReader(responseStream)
'Reading the stream to our string
responseString = stringStreamReader.ReadToEnd.ToString
'Ending the web responce
webResponce.Close()

SQL access to an XL device using HTTP Post vb.net

I am currently working on a project that is supposed to pull data from an XL device to a central location. I emailed the company and they said I need to make an HTTP POST request and parse the returned JSON. Additionally they said that i should make my post request in this format.
POST /sql-request.do HTTP/1.0
Content-Length: 141
response_type=application/json&sql_statement=select sequence_number,
start_time
from timeline_stream order by sequence_number desc limit 5;
I have put what i believe to be this code into vb.net, and I get a response from the server. However it is not the requested table information. Here is the code I am currently using.
Private Sub webRequester()
Dim response As HttpWebResponse = Nothing
Dim replyStreamReader As StreamReader = Nothing
Dim request As HttpWebRequest = HttpWebRequest.CreateHttp("http://192.168.100.223/data/schema/expanded?response_type=application%2Fjson&sql_statement=select%20*%20from%20Intervals")
Dim postData As String = "test"
Dim data() As Byte = UTF8Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.Credentials = New NetworkCredential("User", "Pass")
request.ContentLength = data.Length
request.Method = "POST"
Using requestStream As Stream = request.GetRequestStream
requestStream.Write(data, 0, data.Length)
End Using
response = request.GetResponse()
replyStreamReader = New StreamReader(response.GetResponseStream)
Dim responseFromServer As String = replyStreamReader.ReadToEnd()
Console.WriteLine(responseFromServer)
End Sub
I have also tried using the query string as my postData, but it still returns what seems to be some default response. It is 78 pages when put in word, so here is the first line of the response I am getting.
<?xml version="1.0"?><data_schema><registers><table name="extended_user_strings" number="8" min_rows="1" max_rows="1" defined_by="system" display_name="extended_user_strings_literal" help_text="table_extended_user_strings_copy"><column name="string_1" number="1" index="no" display_name="extended_user_string_1_literal" help_text="extended_user_string_copy" type="string" access="read_write"><restrictions><max_length value="1024" /><pattern value="^[\x20-\xFE]*$" /></restrictions></column><column name="string_10" number="10" index="no" display_name="extended_user_string_10_literal" help_text="extended_user_string_copy" type="string" access="read_write"><restrictions><max_length value="1024"
How can I query the device and get the table I'm looking for?

Trouble with POSTing JSON to endpoint

I'm trying to submit a POST request containing JSON to a given endpoint. However the below code sends me to a login page which is the default functionality for all non-/api endpoints. Because Postman doesn't direct me to the login page but correctly hits the API, I'm assuming the problem is in this C# code.
Dim RemoteUrl As String = "https://my-site.com/api/tournament/results"
Dim result As String = ""
Dim xmlHttpReq As HttpWebRequest = CType(WebRequest.Create(RemoteUrl), HttpWebRequest)
xmlHttpReq.Method = "POST"
xmlHttpReq.ContentType = "application/json"
With (New StreamWriter(xmlHttpReq.GetRequestStream))
.Write(Json)
.Flush()
.Close()
Dim httpResponse As HttpWebResponse = CType(xmlHttpReq.GetResponse(), HttpWebResponse)
With (New StreamReader(httpResponse.GetResponseStream))
result = .ReadToEnd
End With
End With
Any idea what steps I need to take to debug this?

Bad Request 400 when making a token request to Google gmail API

I follow this document to make token request https://developers.google.com/identity/protocols/OAuth2InstalledApp
In the first step, it works fine. I can get the an authentication code.
In the second step, I have a problem with 400 Bad Request. I have been finding answer for this issue for 2 days, but I can't fix the problem.
I set all the properties like the document, but it doesn't matter:
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret=your_client_secret&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
Here is my code:
postData.Clear()
' code is the authentication code in the first request
postData.Add("code=" + code)
postData.Add("client_id=###############.apps.googleusercontent.com")
postData.Add("client_secrect=####################")
postData.Add("redirect_uri=urn:ietf:wg:oauth:2.0:oob")
postData.Add("grant_type=authorization_code")
Dim data As String = String.Join("&", postData.ToArray())
Dim request As HttpWebRequest = HttpWebRequest.Create("https://www.googleapis.com/oauth2/v3/token")
Dim byteData() As Byte = Encoding.UTF8.GetBytes(data)
request.Host = "www.googleapis.com"
request.Method = WebRequestMethods.Http.Post
request.ProtocolVersion = HttpVersion.Version11
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteData.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteData, 0, byteData.Length)
dataStream.Close()
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As Stream = response.GetResponseStream()
response.Close()
Thanks for answer !
I have just found a bug. This's a stupid bug. I typed client_secrect inteads of client_secret. I can't belive it took me 2 days to fix this error.