WebRequest with Bearer Authorization in VB.NET - vb.net

I would need to send a POST request to a remote server, which requires a Bearer Authorization.
this is my VB.NET code:
Public Shared Function syncAsana() As String
Dim result As String
Try
Dim token As String = "TOKEN"
Dim uri As String = "https://URL/api/1.0/tasks"
Dim postData As String = "assignee=email&notes=TEST_NOTES&name=NOME 1&projects=123985"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim request As WebRequest = WebRequest.Create(uri)
request.Method = "POST"
request.PreAuthenticate = True
request.Headers.Add("Authorization", "Bearer " & token)
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()
Using dataStream1 As Stream = response.GetResponseStream()
................
result = responseFromServer
End Using
response.Close()
Catch ex As Exception
result = ex.Message
End Try
Return result
End Function
the problem is that I always get the error The underlying connection was closed: An unexpected error occurred on a receive
the same request made with jquery / ajax or with curl works.
I have tried both from the local server launched by visual studio, and by putting the code on the production server.
could you tell me where i'm wrong?

Related

access API on imagoxt

i must download some information from API exposed by a server, but whit information in my hand i'm very in difficult.
my code :
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim address As Uri
Dim data As StringBuilder
Dim byteData() As Byte
Dim postStream As Stream = Nothing
address = New Uri("https://www.xxxxxxx.com/api/ajax/widget/refreshWidget")
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
request.Method = "POST"
request.Headers("Authorization") = "Bearer " & "owvNGiOautorizzazoGDNHVGpSO2xcVzE8207JqnjNj"
request.Accept = "application/json"
request.ContentType = "multipart/form-data"
request.Host = "www.xxxxxxx.com"
request.ContentType = "application/x-www-form-urlencoded"
request.Headers.Add("userid", "238")
request.Headers.Add("usernodeid", "1036")
request.Headers.Add("dashboardid", "589")
request.Headers.Add("widgetid", "6699")
data = New StringBuilder()
'data.Append("type: " & HttpUtility.UrlEncode("datatable"))
data.Append(body) 'HttpUtility.UrlEncode(body))
byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
request.ContentLength = byteData.Length
Try
postStream = request.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
Finally
If Not postStream Is Nothing Then postStream.Close()
End Try
Try
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Debug.Print(reader.ReadToEnd())
Finally
If Not response Is Nothing Then response.Close()
End Try
with this code i can access to API whit no error,
but i can't receive anythings.

VB.NET ~ PUT WebRequest raising exceptions when trying to GetResponse of it

I am getting TWO exceptions. The first one in the regular code and the second into the exception handling block.
I have this function (below) that supposed to change user settings in a Web API using PUT method. Everything runs fine until the point that I try to get a response from the web request. Then it raises the first exception (unknown) and when I try to handle the error I get a second exception "Object reference not set to an instance of an object".
As far as I know normally what will cause this error is the attempt of getting a response of an unassigned web request, but in this case it IS assigned and the Uri is valid. All the credentials for authorization are correct too.
This is my code:
Try
Dim webRequest As System.Net.HttpWebRequest
webRequest = System.Net.HttpWebRequest.Create(InternalSettings.APIurl + "/config")
webRequest.Headers("Authorization") = InternalSettings.APIpwd
webRequest.Headers("API-Application-Key") = InternalSettings.APIkey
webRequest.Method = "PUT"
webRequest.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = ""
postData += "SaveAllCustomersData=false"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
'The next line will raise an unknown exception
Dim myHttpWebResponse As HttpWebResponse = webRequest.GetResponse
Dim responseReader As StreamReader = New StreamReader(myHttpWebResponse.GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest.GetResponse().Close()
Catch ex As WebException
'The next line will raise a "Object reference not set to an instance of an object" exception
Dim resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
Dim obj = JsonConvert.DeserializeObject(resp)
Return False
End Try
If you are using basic authentification you can try something like this:
Dim strUrl As String = InternalSettings.APIurl + "/config"
Dim request As WebRequest = DirectCast(WebRequest.Create(strUrl), HttpWebRequest)
Dim strResponse As String = ""
Dim byteAuth() As Byte = Encoding.UTF8.GetBytes(InternalSettings.APIkey & ":" & InternalSettings.APIpwd)
Dim strPost As String = "SaveAllCustomersData=false"
Dim bytePost() As Byte = Encoding.UTF8.GetBytes(strPost)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "PUT"
request.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(byteAuth))
Using sw = New StreamWriter(request.GetRequestStream())
sw.Write(bytePost, 0, bytePost.Length)
sw.Flush()
Using response As HttpWebResponse = request.GetResponse()
Using sr = New StreamReader(response.GetResponseStream())
strResponse = sr.ReadToEnd()
End Using
End Using
End Using

API-Problem - POST Json-String with httpClient in VB.net

I want to POST json values via httpClient into an API. Unfortunately I am quite a beginner and can't handle it.
GET works perfectly:
here the code for GET:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
' Wird für https-Requests benötigt
System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim s As String
s = reader.ReadToEnd
Return s
But how do I realize POST?
My API-URL looks like this:
https://mydomaine.net/api/auth?token=467445892587458542...
an i will send an JSON-String {"test":"value1":"test1":"value2"}
I've been working on this problem for many hours.
Can someone please help ???
and here is the code that works
Public Function PostRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim response As String
Dim request As HttpWebRequest
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = contentType
request.Method = method
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

PayPal Get Access Token vb.net The request was aborted: Could not create SSL/TLS secure channel

I have a few questions on calling Grant Access Token API of PayPal, below is my code:
Public Function testAPI() As String
Dim data As StringBuilder
Dim byteData() As Byte
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim postStream As Stream = Nothing
Dim reader As StreamReader
Dim Result As String = ""
request = DirectCast(WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token"), HttpWebRequest)
request.Headers.Add("Username", "XXXXXXXXXX")
request.Headers.Add("Password", "XXXXXXXXXX")
data = New StringBuilder("{""grant_type"":""client_credentials""}")
request.ContentType = "application/x-www-form-urlencoded"
request.Method = WebRequestMethods.Http.Post
byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
request.ContentLength = byteData.Length
postStream = request.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
If Not postStream Is Nothing Then postStream.Close()
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Result = reader.ReadToEnd().ToString
Return Result
End Function
Am I passing Username and Password in right way?
Am I passing "grant_type":"client_credentials" in right way?
I keep getting error: The request was aborted: Could not create SSL/TLS secure channel. I have tried to add some code that I searched from google:
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
request.ProtocolVersion = HttpVersion.Version11
But it still failed and return same error message. Please help.

Error trying to Create ASANA Project in VB.NET

I am getting an error:
400 Bad request
when trying to create a project via vb.net in asana.
Note: The ApiKey I am using works when I use it in other vb.net code to get the list of workspaces which is where I got my workspace ID.
Here is my code; I would be grateful for any insight...
Public Sub main()
Dim address As Uri
address = New Uri("https://app.asana.com/api/1.0/projects")
Dim ApiKey As String
ApiKey = "<my api key>"
Dim basicAuthenticationString As String
basicAuthenticationString = Convert.ToBase64String(New UTF8Encoding().GetBytes(ApiKey + ":"))
' Create the web request
Dim request As HttpWebRequest
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
request.Headers("Authorization") = "Basic " & basicAuthenticationString
request.Method = "POST"
request.ContentType = "application/json"
Dim postData As String = "{""data"":[{""name"":""Randy Test Project"",""notes"":""Randy Test Project Notes"",""workspace"":5272875888767}]}"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As HttpWebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
reader.Close()
dataStream.Close()
response.Close()
Exit Sub
End Sub
I was able to figure it out, My address needed to be:
Dim address As Uri = New Uri("app.asana.com/api/1.0/teams/22956925957833/projects")
Then my postData needed to be:
Dim postData As String = "{""data"":{""name"":""Randy Test Project"",""notes"":""Randy Test Project Notes""}}"
Alternatively, you can specify the team or workspace in the post data. When you get a 400 Bad Request the body of the error response will tell you which fields were actually missing/invalid.