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

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?

Related

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()

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.

vb.net Post login data httpwebrequest and cookies

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.

VB.NET - How To Make a Post to Blogspot Using Blogger API V3?

I'm trying to to make a new post through my vb.net application using blogger api.
But I'm fail every time.
Sometimes it's return 403 forbidden error some times Unauthorised error.
Please Help.
Dim mBlogID As String = "5861877551002158183"
Dim AuthToken As String = "AIza......xxxx..........E6g"
Dim post As String = "{""kind"": ""blogger#post"", ""blog"": { ""id"": """ & mBlogID & """}, ""title"": ""abc-title"", ""content"": ""abc-cont""}"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.googleapis.com/blogger/v3/blogs/" & mBlogID & "/posts?key=" & AuthToken), HttpWebRequest)
request.Method = "POST"
request.ContentLength = post.Length
request.ContentType = "application/json"
request.Headers.Add("Authorization: ", AuthToken) '<--- error here
Using requestStream As Stream = request.GetRequestStream()
Dim postBuffer As Byte() = Encoding.ASCII.GetBytes(post)
requestStream.Write(postBuffer, 0, postBuffer.Length)
End Using
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) '<--- Unauthorised error or 403 error here
Using responseStream As Stream = response.GetResponseStream()
Using responseReader As New StreamReader(responseStream)
'Dim json As String = responseReader.ReadToEnd()
'Dim PostURL As String = Regex.Match(json, """url"": ?""(?<id>.+)""").Groups("id").Value
MsgBox(json) 'want to read json response here.
'MsgBox(PostURL)
End Using
End Using
End Using
This code return this error :Specified value has invalid HTTP Header characters.
Parameter name: name
can anybody fix it? I just want to make a new post to blogger and read its URL.
Project Information:-
Platform: Visual Basic 2010
Blogger API Version: V3
I Suggest view this solution. The post has fully explanations.