WebRequest send file - vb.net

I am consuming an API and, in a POST, I need to send a file.
My function:
Public Sub SendRequest(uri As Uri, jsonDataBytes As Byte())
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
Dim request As WebRequest
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.Method = "POST"
Dim auth = "Basic xxxxxxxxxxx"
request.Headers.Add("Authorization", auth)
request.ContentType = "application/json"
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Try
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
Dim objResponse As Object = reader.ReadToEnd()
End Using
End Using
Catch ex As WebException
End Try
End Using
End Sub
jsonDataBytes is:
Dim data = File.ReadAllBytes(filePath)
But, it does not work. Any help?

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.

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

The request was aborted: Could not create SSL/TLS secure channel (on public site)

Below code fails with the generic error from the title on line where creates the response
Dim httpResponse As HttpWebResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Code below:
Dim URL As String = "https://www150.statcan.gc.ca/t1/wds/rest/getSeriesInfoFromVector"
Dim JsonData As String = "[{""vectorId"":""1038036698""}]"
Dim OutputFile As String = "C:\Temp\1038036698.json"
Public Sub Main()
Dim myRequest As HttpWebRequest = PostJSON(JsonData)
Dim Response As String = GetResponse(myRequest)
System.IO.File.WriteAllText(OutputFile, Response)
End Sub
Private Function PostJSON(ByVal JsonData As String) As HttpWebRequest
Dim objhttpWebRequest As HttpWebRequest
Try
Dim httpWebRequest As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
httpWebRequest.Method = "POST"
httpWebRequest.ContentType = "application/json"
httpWebRequest.MediaType = "application/json"
httpWebRequest.Accept = "application/json"
Using streamWriter As StreamWriter = New StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8)
streamWriter.Write(JsonData)
streamWriter.Flush()
streamWriter.Close()
End Using
objhttpWebRequest = httpWebRequest
Catch ex As Exception
' Console.WriteLine("Send Request Error[{0}]", ex.Message)
Return Nothing
End Try
Return objhttpWebRequest
End Function
Private Function GetResponse(ByVal httpWebRequest As HttpWebRequest) As String
Dim strResponse As String = "Bad Request:400"
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'next line is where it errors out
Dim httpResponse As HttpWebResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Dim StreamReader As StreamReader = New StreamReader(httpResponse.GetResponseStream(), True)
'Dim StreamReader As StreamReader = New StreamReader(DirectCast(httpResponse.GetResponseStream(), String), True)
Dim result As String = StreamReader.ReadToEnd()
strResponse = result.ToString()
Catch ex As Exception
Console.WriteLine("GetResponse Error[{0}]", ex.Message)
Return ex.Message
End Try
Return strResponse
End Function

WebRequest with Bearer Authorization in 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?

Context type error http post visual basic

I have been trying to send an HTTP post to a web service and got this message:
"The 'Content-Type' header must be modified using the appropiat
property or method, Parameter nama:name"
This happens when i try to update a customer with this JSON fotmat :
{"display_name":"john smith","email":"johnsmith#something","company_name":"enterprise"}
This is a part of the code i have been using to connect to the API:
Dim sUrl As String = "https://subscriptions.zoho.com/api/v1/customers"
Dim wHeader As WebHeaderCollection = New WebHeaderCollection()
Dim wRequest As HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(sUrl), HttpWebRequest)
wHeader.Clear()
wHeader.Add("Authorization: Zoho-authtoken 7ca5747efb3be868e155e707e679f9f5")
wHeader.Add("X-com-zoho-subscriptions-organizationid: 397080968")
wHeader.Add("Content-Type: application/json;charset=UTF-8")
wRequest.Accept = "application/json"
MsgBox(wHeader.ToString)
wRequest.Headers = wHeader
wRequest.Method = "POST"
Dim postData As String = sw.ToString
MsgBox(postData)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
wRequest.ContentLength = byteArray.Length
Dim dataStream As Stream = wRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = wRequest.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)
LblResponse.Text = sResponse
Console.WriteLine(sResponse)
reader.Close()
dataStream.Close()
response.Close()
Catch ex As Exception
If ex.InnerException IsNot Nothing Then
LblResponse.Text = ex.Message + " >> " + ex.InnerException.ToString()
Else
LblResponse.Text = ex.Message
End If
End Try
any ideas ?