Here is what I've come up with so far:
Sub GetData()
Try
Dim method As String = calldata("/balances")
MsgBox(method)
Catch ex As Exception
End Try
End Sub
Function calldata(ByVal Method As String) As String
Dim logincookie As CookieContainer
Try
Dim pKey As String = "CODE HERE"
Dim sKey As String = "SECRET CODE HERE"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://api.bitfinex.com/v1/"), HttpWebRequest)
Dim randomn As String = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalSeconds)
'//Dependant upon Method
Dim postData As String = "method=" & Method & "&nonce=" & randomn
Dim tempcookies As New CookieContainer
'//Start Encryption
Dim KeyByte() As Byte = Encoding.ASCII.GetBytes(sKey)
Dim HMAcSha As New HMACSHA384(Encoding.ASCII.GetBytes(sKey))
Dim messagebyte() As Byte = Encoding.ASCII.GetBytes(postData)
Dim hashmessage() As Byte = HMAcSha.ComputeHash(messagebyte)
Dim Sign As String = BitConverter.ToString(hashmessage)
Sign = Sign.Replace("-", "")
'//Generate Post Information
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.Headers.Add("X-BFX-APIKEY", pKey)
postReq.Headers.Add("X-BFX-PAYLOAD")
postReq.Headers.Add("X-BFX-SIGNATURE", LCase(Sign))
postReq.CookieContainer = tempcookies
postReq.ContentType = "application/x-www-form-urlencoded"
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 = messagebyte.Length
'//Send Request
System.Net.ServicePointManager.Expect100Continue = False
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(messagebyte, 0, messagebyte.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())
'The Response Text
Dim thepage As String = postreqreader.ReadToEnd
thepage = thepage.Replace(Chr(34), Chr(39))
Return thepage
Catch
Return False
End Try
End Function
I can't figure out the payload portion. This script is a modified version of what I'm using for other API's. Here is the Bitfinex API info
https://www.bitfinex.com/pages/api
Is everything right except pay load? How do I complete "payload = parameters-dictionary -> JSON encode -> base64" portion of the API details?
Try this.
Sub GetData()
Try
Dim method As String = calldata("/balances")
MsgBox(method)
Catch ex As Exception
End Try
End Sub
Function calldata(ByVal Method As String) As String
Dim logincookie As CookieContainer
Try
Dim pKey As String = "CODE HERE"
Dim sKey As String = "SECRET CODE HERE"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://api.bitfinex.com/v1/balances"), HttpWebRequest)
Dim randomn As String = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalSeconds)
'//Dependant upon Method
Dim postData As String = "{""request"": ""/v1" & Method & """,""nonce"": """ & randomn & """,""options"":{}}"
Dim tempcookies As New CookieContainer
Dim payload As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(postData))
'//Start Encryption
Dim KeyByte() As Byte = Encoding.ASCII.GetBytes(sKey)
Dim HMAcSha As New HMACSHA384(Encoding.ASCII.GetBytes(sKey))
Dim messagebyte() As Byte = Encoding.ASCII.GetBytes(payload)
Dim hashmessage() As Byte = HMAcSha.ComputeHash(messagebyte)
Dim Sign As String = BitConverter.ToString(hashmessage)
Sign = Sign.Replace("-", "")
'//Generate Post Information
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.Headers.Add("X-BFX-APIKEY", pKey)
postReq.Headers.Add("X-BFX-PAYLOAD", payload)
postReq.Headers.Add("X-BFX-SIGNATURE", LCase(Sign))
postReq.CookieContainer = tempcookies
postReq.ContentType = "application/x-www-form-urlencoded"
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 = messagebyte.Length
'//Send Request
System.Net.ServicePointManager.Expect100Continue = False
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(messagebyte, 0, messagebyte.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())
'The Response Text
Dim thepage As String = postreqreader.ReadToEnd
thepage = thepage.Replace(Chr(34), Chr(39))
Return thepage
Catch e As Exception
Return False
End Try
End Function
Related
Public Shared Function GetVolsForMU(ByVal MU As String) As DataTableReader
Dim dataSet As New DataSet
Dim responseData As String
Try
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim reader As StreamReader
request = HttpWebRequest.Create("https://myapi/" & MU)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
request.Headers.Add("Authorization", "Bearer " & ConfigurationManager.AppSettings("BearerToken"))
request.ReadWriteTimeout = 11000
response = request.GetResponse
reader = New StreamReader(response.GetResponseStream)
responseData = reader.ReadToEnd
Catch ex As Exception
My.Utility.LogManager.LogError("VolunteerDAL", "GetVolsForMU", ex)
My.Utility.LogManager.LogInfo("VolunteerDAL", "GetVolsForMU MU was: " & MU)
Throw New My.Exceptions.APIException("Error Calling API.")
End Try
If responseData Is Nothing Then
Return Nothing
End If
Dim volunteers = JsonConvert.DeserializeObject(Of DataTable)(responseData)
Dim tableReader As DataTableReader = dataSet.CreateDataReader(volunteers)
Return tableReader
End Function
My volunteers variable is returning as = {}
responseData = "[{""userId"":""93e4098c-db55-3245-accb-40fe48cd0330"",""firstName"":""Test"",""lastName"":""Tester"",""middleName"":""Super"",""preferredName"":""Test"",""displayName"":""Test"",""pmNumber"":""89332220"",""eMail"":""test#gmail.com"",""username"":""testAPI"",""startDate"":null,""lastLogin"":""2020-08-12T16:25:38.173"",""inactive"":null,""assignmentId"":""334dadbb-bf34-4b92-1783-08da7a5bd456"",""roleId"":""B6CD23CA-7EBF-40FC-99AB-6F91999ABEF5"",""jobName"":""Volunteer"",""jobCodeGroupName"":""Volunteer"",""mU"":""2430"",""expirationDate"":""2023-08-31T00:00:00"",""active"":true}]"
The DataTableReader is coming up empty based off of volunteers not being deserialized correctly. Thanks for any help!
Here's what I ended up with to get it to work.
Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
Dim table As New DataTable()
Dim fields() = GetType(T).GetProperties()
For Each field As PropertyInfo In fields
table.Columns.Add(field.Name, If(Nullable.GetUnderlyingType(field.PropertyType), field.PropertyType))
Next
For Each item As T In list
Dim row As DataRow = table.NewRow()
For Each field As PropertyInfo In fields
row(field.Name) = If(field.GetValue(item) Is Nothing, DbNull.Value, field.GetValue(item))
Next
table.Rows.Add(row)
Next
Return table
End Function
Public Shared Function GetVolsForMU(ByVal MU As String) As DataTableReader
Dim dataSet As New DataSet
Dim responseData As String
Try
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim reader As StreamReader
request = HttpWebRequest.Create("https://myapi/" & MU)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
request.Headers.Add("Authorization", "Bearer " & ConfigurationManager.AppSettings("BearerToken"))
request.ReadWriteTimeout = 11000
response = request.GetResponse
reader = New StreamReader(response.GetResponseStream)
responseData = reader.ReadToEnd
Catch ex As Exception
My.Utility.LogManager.LogError("VolunteerDAL", "GetVolsForMU", ex)
My.Utility.LogManager.LogInfo("VolunteerDAL", "GetVolsForMU MU was: " & MU)
Throw New My.Exceptions.APIException("Error Calling API.")
End Try
If responseData Is Nothing Then
Return Nothing
End If
Dim listOfUserAssignments = JsonConvert.DeserializeObject(Of List(Of UserAssignment))(responseData)
Dim volunteers = ConvertToDataTable(listOfUserAssignments)
Dim tableReader As DataTableReader = dataSet.CreateDataReader(volunteers)
Return tableReader
End Function
The code above is what ended up working for me.
I'm trying to make a github OAuth but it needs some post and get responses.
so how can I make a get request to a specific url an then get the response in form of json,
this is the code that I tried:
Dim logincookie As CookieContainer
Dim rqtp As Integer
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(TextBox1.Text), HttpWebRequest)
Dim postData As String = TextBox1.Text
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim tempCookies As New CookieContainer
postReq.Method = "GET"
postReq.KeepAlive = True
postReq.CookieContainer = tempCookies
postReq.ContentType = "application/xml"
postReq.Referer = TextBox1.Text
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
response.Text = thepage
Clipboard.Clear()
Clipboard.SetText(thepage)
MsgBox(thepage, vbInformation + vbOK, "result")
also if you want you can see the repo so you can see the ful project :)
Ideally deserialize that string to a composite object or to a dymamic object. Your could potentially use JavaScriptSerializer or NewtonSoft library to achieve this and serialize that object to json.
this is the code i have, dim sline from string to json, i have try it and search on google, but i havent done yet...
please help
Dim sURL As String
sURL = TextBox1.Text
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True
wrGETURL.Proxy = myProxy
wrGETURL.Proxy = WebProxy.GetDefaultProxy()
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0
Do While Not sLine Is Nothing
i += 1
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
Console.WriteLine("{0}:{1}", i, sLine)
End If
Loop
Dim respon As Array = sLine.ToArray()
Console.ReadLine()
Console.WriteLine(respon("traceNo"))
Console.ReadLine()
i want to convert the Dim sline to json, how it possible?
Newtonsoft.JSON is a VERY handy NuGet to easy use JSON in VB.Net.
Seperate your lines into a List(Of Integer, String) (i,sLine)
and Serialize it with
Dim yourJSONString = JsonConvert.SerializeObject(yourList)
Im looking to get a list of all the devices on my work admin teamviewer account using vb.net. I would also like to be able to change the "Alias" of a given device using it's device id. i know very little about API's. i found the following example but i am not sure how to adapt it to get the json response.
instead of the accesstoken, i believe i need to use the client id and secret id along with the authorization code in order to use this. if i run it in it's current start i get a 401 unauthorized error. Any help would be appreciated.
i also have no idea how to use "PUT" to change the Alias using the device id which will both be entered in textboxes. ex alias = textbox1.text and device_id = textbox2.text
Private Sub SurroundingSub()
Dim accessToken As String = "xxxxxxxxxxxxxxxxxxx"
Dim apiVersion As String = "v1"
Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com"
Dim address As String = tvApiBaseUrl & "/api/" & apiVersion & "/devices"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Bearer", accessToken)
request.Method = "GET"
Dim webResp As WebResponse = request.GetResponse()
Catch __unusedException1__ As Exception
msgbox(__unusedException1__.ToString)
End Try
End Sub
Here is the Get all devices code:
Private Sub get_teamviewer_devices()
Dim accessToken As String = "XXXXXXXXXXXXXXXXXXXXX"
Dim apiVersion As String = "v1"
Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com"
Dim address As String = tvApiBaseUrl & "/api/" & apiVersion & "/devices"
Dim result_json As String = Nothing
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "GET"
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result_json = reader.ReadToEnd()
End Using
TextBox1.Text = result_json
Catch __unusedException1__ As Exception
MsgBox(__unusedException1__.ToString)
End Try
End Sub
Here is the PUT portion to change an alias:
Public Sub change_alias(ByVal device_id As String, ByVal alias_str As String)
Dim accessToken As String = "XXXXXXXXXXXXXXXXXXXXX"
Dim apiVersion As String = "v1"
Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com"
Dim address As String = tvApiBaseUrl & "/api/" & apiVersion & "/devices/" & device_id
Dim result As String
Dim alias_str_ As String = Chr(34) & alias_str & Chr(34)
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "PUT"
request.ContentType = "application/json"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write("{""Alias"" : " & alias_str_ & "}")
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch __unusedException1__ As Exception
MsgBox(__unusedException1__.ToString)
End Try
End Sub
I have this code in my project:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = rawresp
and TextBox2 gets the JSON code correctly.
and this is my JSON code example:
{
"id":174543706,
"first_name":"Hamed",
"last_name":"Ap",
"username":"hamed_ap",
"type":"private"
}
My question:
How to get 174543706 from JSON code ("id") into TextBox3.Text???
You could use JavaScriptSerializer which is in System.Web.Script.Serialization.
Imports System.Web.Script.Serialization
Module Module1
Sub Main()
Dim s As String
Try
Dim rawresp As String = "{""id"":174543706,""first_name"":""Hamed"",""last_name"":""Ap"",""username"":""hamed_ap"",""type"":""private""}"
Dim jss As New JavaScriptSerializer()
Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)
s = dict("id")
Catch ex As Exception
End Try
End Sub
End Module
try this code :
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
Dim firstItem = jsonResulttodict.item ("id")
hope it help you !!
How to get 174543706 from JSON code ("id") into TextBox3.Text?
{
"id": 174543706,
"first_name": "Hamed",
"last_name": "Ap",
"username": "hamed_ap",
"type": "private"
}
Sorry if my reply was late. I hope my answer can help someone who's still confused.
So what you do was get the response and read the JSON.
After you do ReadToEnd():
Dim xr As XmlReader = XmlReader.Create(New StringReader(rawresp))
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(rawresp)
Then What you need to do is to read the data from the response. you do like this:
Dim res As String = JsonConvert.SerializeXmlNode(doc)
Dim ThisToken As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(res)
Dim response As String = ThisToken("response").ToString()
Dim ThisData As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(response)
After that yo can get the data from the response and convert it into string
Dim idx As String = ThisData("id").ToString()
// the value of idx will be: 174543706
Then last you can put it into Texbox3.Text.
JSON can be parsed using adding Newtonsoft.Json.dll reference
Code :
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim json As String = New System.Net.WebClient().DownloadString("http://time.jsontest.com/")
Dim parsejson As JObject = JObject.Parse(json)
Dim thedate = parsejson.SelectToken("date").ToString()
txt1.Text = "Date Is "+thedate
End Sub
End Class
Reference : Narendra Dwivedi - Parse JSON
This works:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = JObject.Parse(rawresp)("id")