Curl URL into vb.net - vb.net

Hi i'm trying to find a solution how to implement the below curl in vb.net:
curl -X 'GET' \ 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full' \ -H 'accept: application/json'

Using System.Net.Http you can do that as follows:
Private Sub GetBtcPrice()
Using client As System.Net.Http.HttpClient = New System.Net.Http.HttpClient
client.DefaultRequestHeaders.Add("accept", "application/json")
Dim sb As New StringBuilder
sb.Append("?")
sb.Append("ids=bitcoin&")
sb.Append("vs_currencies=usd&")
sb.Append("include_market_cap=false&")
sb.Append("include_24hr_vol=false&")
sb.Append("include_24hr_change=false&")
sb.Append("include_last_updated_at=false&")
sb.Append("precision=full")
Dim response As HttpResponseMessage = client.GetAsync("https://api.coingecko.com/api/v3/simple/price" & sb.ToString).GetAwaiter().GetResult()
Dim sResponse As String = response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
Console.WriteLine("response: " & sResponse)
End Using
End Sub

Dim webClient As New System.Net.WebClient
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim result As String = webClient.DownloadString("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full")
And its stored in variable result as json

Related

Unable to create a cURL string in VB.net

I I'm trying to integrate an SMS service in my desktop application in VB.net but I'm not able to create the correct string to to that.
This is the autentication method:
Session Key example
curl -XGET 'https://app.esendex.it/API/v1.0/REST/login' -H 'Content-Type: application/json'
-H 'Authorization: Basic base64_encode(MY_USERNAME:MY_PASSWORD)'
On success, the above command returns the following response: USER_KEY;SESSION_KEY
This is what I've done:
Private Sub SMS()
Dim username = "myuser"
Dim password = "mypass"
Dim encoded As String
encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password))
Dim webRequest As WebRequest = WebRequest.Create("https://app.esendex.it/API/v1.0/REST/login")
webRequest.ContentType = "application/json"
webRequest.Headers.Add("Authorization", "Basic " + encoded)
webRequest.Method = "GET"
Dim myHttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
TextBox1.Text = myHttpWebResponse.ToString
End Sub
but myHttpWebResponse.ToString doesn't get USER_KEY & SESSION_KEY
Can someone help me ?

Correct way to add "autorization : bearer" header in an HttpWebRequest

Context
I want to code this curl command in VB.NET
curl -X GET 'https://api.twitch.tv/helix/users?login=crunchprank' \
-H 'Authorization: Bearer YY' \
-H 'Client-Id: XX'
This curl works perfectly if executed in online curl like https://reqbin.com/curl
Client Id and Bearer are ok.
Here is my VB.Net code
Dim strTwitchApiRequestChannelUrl As String
Dim httpTwitchApiRequestChannel As HttpWebRequest
Dim httpTwitchApiRequestChannelResponse As HttpWebResponse
Dim strTwitchApiRequestChannelResponse As String
strTwitchApiRequestChannelUrl = "https://api.twitch.tv/helix/users?" & strTwitchChannelId
httpTwitchApiRequestChannel = CType(WebRequest.Create(strTwitchApiRequestChannelUrl), HttpWebRequest)
httpTwitchApiRequestChannel.Timeout = 10000
httpTwitchApiRequestChannel.Headers("client_id") = "XX"
httpTwitchApiRequestChannel.Headers("Authorization") = " Bearer " & YY
httpTwitchApiRequestChannelResponse = TryCast(httpTwitchApiRequestChannel.GetResponse(), HttpWebResponse)
If httpTwitchApiRequestChannelResponse.StatusCode = 200 Then
Using responseStream As Stream = httpTwitchApiRequestChannelResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(responseStream)
strTwitchApiRequestChannelResponse = reader.ReadToEnd()
End Using
End If
Issue:
I get an 401 response code. I'm pretty sure it's because of the autorization headers. It missed the :
Same issue if i did this :
httpTwitchApiRequestChannel.Headers("Authorization") = ": Bearer " & YY
And I cannot do this httpTwitchApiRequestChannel.Headers("Authorization: Bearer ") = YY because i got an error: Specified value has invalid HTTP Header characters. (Parameter 'name')"}

converting curl -x get to vb.net without success

I need to convert this to vb.net:
curl -X GET --header 'Accept: application/json' --header 'X-API-KEY: xxxxxxxxxxxxxxxx' 'https://app.atera.com/api/v3/agents'
What I've tried is:
Dim myHttpWebRequest = CType(WebRequest.Create("https://app.atera.com/api/v3/agents"), HttpWebRequest)
myHttpWebRequest.Headers.Add("Accept", "application/json")
myHttpWebRequest.Headers.Add("X-API-KEY", "XXXXXXXXXXXXXXX")
Dim myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
TextBox1.Text = myHttpWebResponse.ToString
Unfortunatly whatever I tried I get an error.
Can you help me out here?
Got it worked.
They new code that works is:
Dim myHttpWebRequest = CType(WebRequest.Create("https://app.atera.com/api/v3/agents/130"), HttpWebRequest)
myHttpWebRequest.Accept = "application/json"
'myHttpWebRequest.Headers.Add("Accept", "application/json")
myHttpWebRequest.Headers.Add("X-API-KEY", "XXXXXXXXXXXX")
Dim myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Dim responseReader As StreamReader = New StreamReader(myHttpWebResponse.GetResponseStream)
Dim result As String = responseReader.ReadToEnd()
TextBox1.Text = result
End Sub

Translate Curl's --key and --cert to VB.NET

I need to post via VB.NET two files, a key file and a pem file, this can be done via Curl with the command:
curl https://someWebSite.com/test --key ./private_key.key --cert ./certificate.pem -d grant_type=password -d username="" -d password=""
So far I've done this in VB.NET but it just pops an error that says "Additional information: The remote server returned an error: (401) Unauthorized.
i reached one example where they use a *.p12 file and i tried to recreate it in VB.NET but still saying the same error. This is my Code:
Dim token As String = ""
Dim uriVar As New Uri("https://someWebSite.com/test")
Dim user As String = ""
Dim password As String = ""
Dim request As HttpWebRequest = CType(WebRequest.Create(uriVar), HttpWebRequest)
request.KeepAlive = False
request.ProtocolVersion = HttpVersion.Version11
request.Method = "POST"
Dim credential As New NetworkCredential(user, password)
request.Credentials = credential
Dim keystoreFileName As String = "keystore.p12"
Dim pathCert As String = Path.Combine(Environment.CurrentDirectory, "cert\", keystoreFileName)
Dim cert As New X509Certificate(pathCert, "allpassword")
request.ClientCertificates.Add(cert)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = 39
request.Accept = "*/*"
Dim requestStream As Stream = request.GetRequestStream()
Dim post_data As String = "grant_type=password&username=&password="
Dim postBytes As Byte() = Encoding.ASCII.GetBytes(post_data)
requestStream.Write(postBytes, 0, postBytes.Length)
requestStream.Close()
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) 'Here pops the error...
Dim responseJson = New StreamReader(response.GetResponseStream()).ReadToEnd()
Return responseJson

How to log into router with HttpWebRequest?

I'm trying to figure out how to successfully log into a DSL-Router (Model: Speedport w504v Type A).
I wrote a function usinig HttpWebRequest and HttpWebResponse. So far this function is not finished and is only for finding out the right login process.
Public Function DoRequest(ByVal url As String, ByVal password As String, ByVal container As CookieContainer) As String
'Login Request
Dim reqLogin As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://speedport.ip/cgi-bin/login.cgi"), HttpWebRequest)
reqLogin.CookieContainer = container
reqLogin.Method = "POST"
reqLogin.Referer = "https://speedport.ip/hcti_start_passwort.stm"
reqLogin.KeepAlive = True
reqLogin.Host = "speedport.ip"
reqLogin.ContentType = "application/x-www-form-urlencoded"
reqLogin.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
reqLogin.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3")
reqLogin.Headers.Add("Accept-Encoding", "gzip, deflate")
'Login Data
Dim encoding As New ASCIIEncoding()
Dim data As String = Uri.EscapeDataString("pws") & "=" & Uri.EscapeDataString(password)
Dim bytes As Byte() = encoding.GetBytes(data)
reqLogin.ContentLength = bytes.Length
Dim stream As Stream = reqLogin.GetRequestStream
stream.Write(bytes, 0, bytes.Length)
stream.Close()
'Login Response
Dim resLogin As HttpWebResponse = DirectCast(reqLogin.GetResponse(), HttpWebResponse)
'Receive Cookie
Dim CookieHeaderValue As String = reqLogin.Headers.Get("Cookie")
If CookieHeaderValue <> Nothing Then
Dim aCookie As String() = CookieHeaderValue.Split("=")
Dim Cookie As New Cookie
Cookie.Domain = "speedport.ip"
Cookie.Path = "/"
Cookie.Secure = True
Cookie.Name = aCookie(0)
Cookie.Value = aCookie(1)
container.Add(Cookie)
End If
'Url Request
Dim reqIndex As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
reqIndex.CookieContainer = container
reqIndex.Method = "GET"
reqIndex.Referer = "https://speedport.ip/wait_login.stm"
reqIndex.KeepAlive = True
reqIndex.Host = "speedport.ip"
reqIndex.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
'Url Content
Dim resIndex As HttpWebResponse = DirectCast(reqIndex.GetResponse(), HttpWebResponse)
Dim sr As StreamReader = New StreamReader(resIndex.GetResponseStream())
Dim output As String = sr.ReadToEnd
resIndex.Close()
Return output
End Function
Unfortunately I don't get the right content. Instead I'm getting the sitecontent from an Error-Page saying:
double administration access!
This site is returned when you try to login but there is another session already running.
So maybe I'm already successfully logged in but don't get the site content.
I get the header information from an Firefox AddOn called HTTP Live Header.
I also tried to run curl but also did not work:
curl -d "pws=PASSWORD" -c cookies.txt -e https://speedport.ip/hcti_start_passwort.stm -k https://speedport.ip/cgi-bin/login.cgi
curl -c cookies.txt -e https://speedport.ip/wait_login.stm -k https://speedport.ip/index.stm
Maybe someone has an idea what's going wrong.
Using Fiddler I figured it out. I've to set also the User Agent Header for the first request.
reqLogin.UserAgent = "YOUR USERAGNET STRING"
Furthermore I don't have to get the value for reqLogin.Headers.Get("Cookie").
It's already set to the CookieContainer so cancel the "Receive Cookie" part.