Reading from API using VB.NET - 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()

Related

error 'The given key was not present in the dictionary' when trying to API HTTP request token with Blue Prism

Im trying to use the Blue Prism object HTTP request to get an access token for further processing the items. However, i couldn't manage to get the token due to the error 'The given key was not present in the dictionary'. I have looked all parameters and still didn't manage to solve the issue. I use a built in visual basic code to get the result as a collection which is later parsed to JSON to get the token.
The underlying visual basic code is:
Dim request As WebRequest = WebRequest.Create(addressURL)
If forcePreAuth Then
'Sometimes a web server will require the authorisation header in the initial request
'In which case we have to add the basic authorization header manually.
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}",username,password))
Dim base64 As String = Convert.ToBase64String(bytes)
request.Headers.Add("Authorization", "Basic " & base64)
Else
If Not String.IsNullOrEmpty(username) AndAlso Not String.IsNullOrEmpty(password) Then
request.Credentials = New NetworkCredential(username,password)
End If
End If
If useProxy Then
Dim proxyURI As New Uri(proxyURL)
Dim proxy As New WebProxy(proxyURI, True)
Dim proxyCred As New NetworkCredential(proxyUsername, proxyPassword)
Dim credCache As New CredentialCache()
credCache.Add(proxyURI, "Basic", proxyCred)
proxy.UseDefaultCredentials = False
proxy.Credentials = credCache
request.Proxy = proxy
End If
request.Method = method
request.ContentType = contentType
Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest)
If httpRequest IsNot Nothing Then
If Not String.IsNullOrEmpty(accept) Then
httpRequest.Accept = accept
End If
If Not String.IsNullOrEmpty(certID) Then
httpRequest.ClientCertificates.Add(m_Certificates(certID))
End If
End If
For Each r As DataRow In headers.Rows
For Each c As DataColumn In headers.Columns
Dim columnName As String = c.ColumnName
Dim val As String = r(columnName).ToString
request.Headers.Add(columnName,val)
Next
Exit For 'Only one row is allowed
Next
If Not String.IsNullOrEmpty(body) Then
Dim requestStream As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(requestStream, New Text.UTF8Encoding(False))
sw.Write(body)
End Using
End If
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
End Using
Screenshots:
Input parameter
Input parameter request token
Request token:
Output parameter:
Blue Prism uses a bit of a peculiar pattern regarding Certificates. The way the Utility - HTTP object is designed is to allow for the loading of certificate files (.cer, etc) on-the-fly into a local Certificate Store, which assigns a new Certificate ID each time.
Before firing your HTTP Request, use the Load Certificate action within the same Utility - HTTP object to output a valid Certificate ID, which you can then pass to HTTP Request's Certificate ID parameter.

Create SOAP request with vb.net

I'm trying to call a webservice in vb.net and I have followed this thread: WebService Send SOAP request and received response using visual Basic
These are the steps that I have followed:
I have already add the reference to the project (http://webservice_url?wsdl).
I have written the soap request in an xml file by hand (I attach the xml file as image here )
I have load the xml file into an string variable and call to the webservice like that:
Dim strDocumentoSoap As String
Dim document As XDocument = XDocument.Load("C:\myFile.xml")
strDocumentoSoap = document.ToString
Dim servicioWeb As svc.v79jIntegracionPerfilSesion = New svc.v79jIntegracionPerfilSesion
Dim sbLogin As New System.Text.StringBuilder
sbLogin.Append(strDocumentoSoap)
Dim hwrequest As System.Net.HttpWebRequest
hwrequest = System.Net.WebRequest.Create("http://myServiceURL/realizarPeticionPublicacionOSBUS?WSDL")
hwrequest.Method = "POST"
hwrequest.ContentType = "text/xml; charset=utf-8"
Dim byteData As Byte() = System.Text.Encoding.UTF8.GetBytes(sbLogin.ToString())
hwrequest.ContentLength = byteData.Length
Dim writer As Stream = hwrequest.GetRequestStream
writer.Write(byteData, 0, byteData.Length)
writer.Close()
Dim Response As System.Net.HttpWebResponse
Response = hwrequest.GetResponse
Dim responseStatus As String = Response.StatusDescription.ToString
Dim DataStream As Stream
Dim Reader As StreamReader
DataStream = Response.GetResponseStream()
Reader = New StreamReader(DataStream)
Dim SD2Request As String = Reader.ReadToEnd()
'SHOW THE RESPONSE INTO MSGBOX
MsgBox(SD2Request)
This works perfectly, but I have read in the internet that this practice is not recommended (hand made XML for SOAP), because there are other useful tools in .net.
Can anyone explain me other options or libraries for creating a soap request in VB.NET without creating the soapenvelope by hand.
Thank you very much in advance!
Marga

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.

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?

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.