I am trying to take a Curl example and make it work from within VB.Net using Visual Basic in VS 2022 Community. I have tried everything that I can think of to make this work, but everything returns 400 (Bad Request). My first thoughts concerned the "data" of the request. The target site's example has this:
curl --location '/v2/Upload/FilesBase64' \
--header 'Content-Type: application/json' \
--data '{
"transmitter": {
"username": "",
"password": ""
},
"simulateUpload": true,
"files": [
{
"fileName": "TEST_dummy1.txt",
"ContentType": "text/plain",
"fileContentBase64": "ZHVtbXk="
}
]
}'
Which I duplicated with the following code in VB:
'Get the file content
Dim FileData As String() = {IO.File.ReadAllText(FullFileName)}
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(FileData(0))
Dim Content As String = Convert.ToBase64String(byt)
'Build the body of the request
Dim Dta As New Dictionary(Of Object, Object)
Dim Transmitter As New Dictionary(Of Object, Object) From {
{"username", USR},
{"password", PWD}
}
Dta.Add("trasnmitter", Transmitter)
Dta.Add("simulateUpload", True)
Dim FileListarray As New List(Of Object) From {
New Dictionary(Of Object, Object) From {
{"filename", "TEST_DataFile.txt"},
{"ContentType", "text/plain"},
{"filecontentbase64", Content}
}
}
Dta.Add("files", FileListarray.ToArray)
Dim Body As String = JsonConvert.SerializeObject(Dta, Formatting.Indented)
Dim BodyBytes As Byte() = Encoding.UTF8.GetBytes(Body)
Which produced the following (formatted here for clarity):
{
"trasnmitter": {
"username": "xxxxxxx",
"password": "xxxxxxx"
},
"simulateUpload": true,
"files": [
{
"filename": "TEST_DataFile.txt",
"ContentType": "text/plain",
"filecontentbase64": "MUYgICAg=="
}
]
}
Lastly, I use this code to sent and retrieve the response:
Dim BodyBytes As Byte() = Encoding.UTF8.GetBytes(Body)
'build the web request
Dim URL As String = BaseURL & "/v2/Upload/FilesBase64"
Dim WebRequest As Net.WebRequest = WebRequest.Create(URL)
WebRequest.ContentType = "application/json"
WebRequest.Method = "POST"
WebRequest.ContentLength = Body.Length
'transmit the request
Dim Stream As Stream = WebRequest.GetRequestStream()
Stream.Write(BodyBytes, 0, Body.Length)
Stream.Close()
'get the response
Dim ServerText As String = ""
Try
Dim Response As WebResponse = WebRequest.GetResponse
Dim ResponseStream As New StreamReader(Response.GetResponseStream)
ServerText = ResponseStream.ReadToEnd
Catch ex As Exception
Dim ttt = ""
End Try
Please note, this is still highly in development, and I haven't expanded the error handling. If anyone has any ideas on what is wrong, please let me know!
JSON is case-sensitive. Your JSON differs from the sample JSON in its case.
Your ContentLength
is also wrong, should be BodyBytes.Length
, not Body.Length
, in both the assignment of WebRequest.ContentLength
and the call to Stream.Write
.
Unrelated to your question, but you should be Using
the request and response streams.