How to translate this cURL command to a VB? - vb.net

I'm trying to translate the following cURL command that extrats a .diff content in GitHub to VB:
curl -H 'Authorization: token myGitHubToken' -H "Accept: application/vnd.github.v3.diff" https://api.github.com/repos/[USR]/[REPO]/commits/[COMMITID]
The cURL works fine. And my code in VB with HttpWebRequest is
Dim url As New Uri("https://api.github.com/repos/[USR]/[REPO]/commits/[COMMITID]")
Dim myReq As HttpWebRequest = HttpWebRequest.Create(url)
SetAllowUnsafeHeaderParsing20()
myReq.Headers.Add("Authorization: token myGitHubToken")
myReq.Accept("application/vnd.github.v3.diff")
myReq.KeepAlive = False
Dim response As HttpWebResponse = CType(myReq.GetResponse(), HttpWebResponse)
But in GetResponse, throws me a WebException :
"The remote server returned an error: (403) Forbidden"
Is ok my traslation? There is something wrong?

Related

use HttpClient (POST) in vb.net to write data to InfluxDB v2.4

I want to do this (works):
curl --request POST "http://192.168.1.99:8086/api/v2/write?org=db1&bucket=data&precision=ns" --header "Authorization: Token 12345..." --header "Content-Type: text/plain; charset=utf-8" --header "Accept: application/json" --data-binary "solar,mytag=1 cwatt=125"
in vb.net without using influx library. I tried this:
Dim httpClient As HttpClient = New HttpClient()
Dim DAhttpContent As StringContent = New StringContent("solar,mytag=1 cwatt=222", Encoding.UTF8, "text/plain")
DAhttpContent.Headers.Add("Authorization:", "Token 12345...")
DAhttpContent.Headers.Add("Content-Type:", "text/plain; charset=utf-8")
DAhttpContent.Headers.Add("Accept:", "application/json")
Dim response = httpClient.PostAsync("http://192.168.1.99:8086/write?db=data&u=user1&p=writewrite1", DAhttpContent)
Error-> System.FormatException: "The header name format is invalid."
So I read many topics here on overflow and tried something else:
Private Shared Async Function Main3() As Task
Using xclient As HttpClient = New HttpClient()
Dim request_json = "solar,mytag=1 cwatt=222"
Dim content = New StringContent(request_json, Encoding.UTF8, "text/plain")
Dim authenticationBytes = Encoding.ASCII.GetBytes("12345...")
xclient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", Convert.ToBase64String(authenticationBytes))
xclient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim result = Await xclient.PostAsync("http://192.168.1.99:8086/api/v2/write?org=db1&bucket=data&precision=ns", content)
'Dim result_string As Task(Of String) = result.Content.ReadAsStringAsync() '<- Error "Content is no Member of Task(Of HttpResponseMessage)"
End Using
End Function
It runs without any error but also does not writes any data. So my problems are:
how to authenticate in Header correctly?
wait/return response outside Async function
Maybe it's easier to do by UDP (8089) packet transmission?
Any vb.net code example would be very helpful for me.
(I also cheked many similar questions here before.)
Thanks in advance!

How to convert this CURL request to VB.NET code

I am trying to upload a file to MixCloud using their API. In their documentation following curl request is the only example. I want this request to convert to VB.net WebRequest or other method. I need it in VB.net language. I tried everything including HttpResponseMessage but it reruns an error like bad request. Please help.
curl -F mp3=#upload.mp3 \
-F "name=API Upload" \
-F "tags-0-tag=Test" \
-F "tags-1-tag=API" \
-F "sections-0-chapter=Introduction" \
-F "sections-0-start_time=0" \
-F "sections-1-artist=Artist Name" \
-F "sections-1-song=Song Title" \
-F "sections-1-start_time=10" \
-F "description=My test upload" \
https://api.mixcloud.com/upload/?access_token=INSERT_ACCESS_TOKEN_HERE
I added VB.net code created using the method mentioned by #Martheen and I found the solution. Also I had to add
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
To allow TLS
This is final working code
Public Async Sub Upload(username As String, fileName As String, songTitle As String, description As String, accessToken As String)
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Using httpClient = New HttpClient()
Using request = New HttpRequestMessage(New HttpMethod("POST"), "https://api.mixcloud.com/upload/?access_token=" & accessToken)
Dim multipartContent = New MultipartFormDataContent()
multipartContent.Add(New ByteArrayContent(File.ReadAllBytes(fileName)), "mp3", Path.GetFileName(fileName))
multipartContent.Add(New StringContent(songTitle), "name")
multipartContent.Add(New StringContent(description), "description")
request.Content = multipartContent
Dim response = Await httpClient.SendAsync(request)
End Using
End Using
Catch ex As Exception
MsgBox(ex.InnerException.Message)
End Try
End Sub

ERROR: The remote server returned an error: (400) Bad Request

I am using aspx vb .net to connect with instagram api
I am using the following link as references: https://code.msdn.microsoft.com/Haroon-Said-e1d8d388
ERROR: The remote server returned an error: (400) Bad Request.
It is weird becuase i followed all steps and imported json as showed in above link. any idea? below is my code:
Dim json As String = ""
Try
Dim parameters As New NameValueCollection
parameters.Add("client_id", Client_ID)
parameters.Add("client_secret", ClientSecret)
parameters.Add("grant_type", "authorization_code")
parameters.Add("redirect_uri", Redirect_URI)
parameters.Add("code", Code)
Dim client As WebClient = New WebClient()
Try
'ERROR HERE
Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)
...
Catch ex As Exception
labelTest.Text += "---" & ex.Message
End Try
Thanks. yeah I been working on this for couple months now and trying to debug but I just have no idea whats going on. I mean I looked at insta api webbsite sill no luck. I tested my values also and they seem to be correct:
curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
client_secret = f208d9fc9cec4b69bdd5f8f1386a
client_secret = d836619eede4490fd12983b95961
grant_type = authorization_code
redirect_uri = http://localhost:1861/UI/Home.aspx
code = 6185508825da0c28a33ac5dcc77
note, 'code' i am getting when when user logs into insta. I used the following url to get the code:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
I know authorize is correct becuase it gives me code in url
solved!
just changed response_type from code to token... it will give you access_token

Square API with Vb.net

Dim myUri = New Uri("https://squareup.com/v2/locations")
Dim RQ As HttpWebRequest = TryCast(WebRequest.Create(myUri), HttpWebRequest)
RQ.PreAuthenticate = True
RQ.Headers.Add("Authorization", "Bearer" & Token) '''Token is a Shared string assigned to my current Access Token
RQ.Method = "GET"
RQ.Accept = "application/json"
RQ.ContentType = "application/json"
Using response As HttpWebResponse = TryCast(RQ.GetResponse(), HttpWebResponse) '''''"The remote server returned an error: (404) Not Found."
Very new to the Square-Connect API and there are no vb.net examples so this was as far as i can get. Im not able to get pass the last line. I always get a 404 error no matter what i try. Anyone know why.
If I use this command (replacing Token with my access Token), in a terminal then I get the result I want in vb.net.
curl -H "Authorization: Bearer Token" https://connect.squareup.com/v2/locations
The guys at square quickly found my problem so here is the working code:
Dim myUri = New Uri("https://connect.squareup.com/v2/locations")
Dim RQ As HttpWebRequest = TryCast(WebRequest.Create(myUri), HttpWebRequest)
RQ.PreAuthenticate = True
RQ.Headers.Add("Authorization", "Bearer " + Token) 'Token is a Shared string assigned to my current Access Token
RQ.Method = "GET"
RQ.Accept = "application/json"
RQ.ContentType = "application/json"
Using response As HttpWebResponse = TryCast(RQ.GetResponse(), HttpWebResponse)

The 'Accept' header must be modified using the appropriate property or method - TwitchAPI

My problem, as you can see in the title, is I get an exception when adding the header. What I'm trying to do is send an authorization request to the public TwitchAPI. Here's the request that I'm trying to translate:
curl -H 'Accept: application/vnd.twitchtv.v3+json'
-H 'Authorization: OAuth <access_token>' \
-X GET https://api.twitch.tv/kraken/channel
It's when I add the Accept header where this exception pops up in my face (title). I'm not sure if I've translated this correctly but this is the code I have right now:
Dim wr = CType(WebRequest.Create("https://api.twitch.tv/kraken/channel"), HttpWebRequest)
wr.Method = "GET"
wr.Headers.Add("Authorization: OAuth <oauth_token>")
wr.Headers.Add("Accept: application/vnd.twitchtv.v3+json")
Return CType(wr.GetResponse(), HttpWebResponse)
where oauth_token is my access token, anyone who could solve this for me? Really worked my ass off trying to figure out such a simple thing, thanks!
Oh and also, when I remove the header (which I actually think is unnecessary) it says im unauthorized, using the correct access token.
The HttpWebRequest class has a specific Accept property for setting the 'Accept' header
Dim wr = CType(WebRequest.Create("https://api.twitch.tv/kraken/channel"), HttpWebRequest)
wr.Method = "GET"
wr.Headers.Add("Authorization: OAuth <oauth_token>")
wr.Accept = "application/vnd.twitchtv.v3+json"
Return CType(wr.GetResponse(), HttpWebResponse)