VB.NET File upload using WebApi: UnExpected end of MIME - vb.net

Everything seems to be working except I get this below error in the WEBAPI:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
When I upload the same file from postman to the WEBAPI endpoint it works perfectly. Makes me think its a problem with the VB application.
BTW: Not skilled in VB (Inherited Application trying to make it work to upload large files)
Dim fileBytes As Byte() = Nothing
Dim boundary As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
Using binaryReader As New BinaryReader(fileUpload1.PostedFile.InputStream)
fileBytes = binaryReader.ReadBytes(binaryReader.BaseStream.Length)
binaryReader.Close()
End Using
Dim request As HttpWebRequest =
WebRequest.Create("http://mylocalhost/api/directory")
request.Method = "POST"
request.ContentType = "multipart/form-data; boundary = " + boundary
request.ContentLength = fileBytes.Length
request.Accept = "*/*"
request.AutomaticDecompression = DecompressionMethods.GZip
request.KeepAlive = True
Dim newStream As IO.Stream = request.GetRequestStream()
newStream.Write(fileBytes, 0, fileBytes.Length)
'newStream.Close()
Dim response As WebResponse = request.GetResponse()
' Display the status.
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
Dim dataStream As IO.Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
Debug.WriteLine("File uploaded")
Return True````

Related

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

VB POST request whit form-control values

I am having different problems when trying to make a POST request to my API, the API works perfectly tested in postman.
I would like to know if anyone sees that I am doing wrong, thank you very much
Dim url As String = "http://0.0.0.0/connect"
Dim dataToPassFromFormData As String = "client_id=1020&client_secret=FF29D58E&grant_type=password&username=admin&password=123"
Dim enc As UTF8Encoding
Dim postdatabytes As Byte()
Dim request As HttpWebRequest = TryCast(WebRequest.Create(url), HttpWebRequest)
enc = New System.Text.UTF8Encoding()
postdatabytes = enc.GetBytes(dataToPassFromFormData)
request.Method = "POST"
request.ContentLength = postdatabytes.Length
Using stream = request.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim receiveStream As Stream = response.GetResponseStream()
Dim readStream As StreamReader = New StreamReader(receiveStream, Encoding.UTF8)
Dim us As user
us = JsonConvert.DeserializeObject(Of user)(readStream.ReadToEnd())
response.Close()
readStream.Close()
Return us.access_token
My api expects these parameters by body / form-data
client_id=1020
client_secret=FF29D58E
grant_type=password
username=admin
password=123

VB POST REQUEST

I am having different problems when trying to make a POST request to my API, the API works perfectly tested in postman.
I would like to know if anyone sees that I am doing wrong, thank you very much
Dim request As WebRequest = WebRequest.Create("http://0.0.0.0/connect")
request.Method = "POST"
Dim postData As String = "client_id=1&client_secret=F&grant_type=password&username=usuario&password=123&scope=Profile offline_access PaymentBO&provider=PersonalOld"
Dim postdatabytes As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentLength = postdatabytes.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(postdatabytes, 0, postdatabytes.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
response.Close()
Return responseFromServer
The api responds to me (attached image)

login to Huawei Wingle e8231s - 2 with vb.net return login error

I'm trying to send sms from win7 pc/64bit, visual studio 2015, vb.net,
using Huawei Wingle e8231s - 2 GSM Wifi Stick,
The GSM Wifi Stick web interface makes calls to API that I'm trying to mimic.
To do so, a Login request must done first, with header contains both verification token and cookie(session id), which I can get by requesting from the wingle webserver.
I always have The response code is 108006 which is incorrect username or password.
My code:
Public Sub Main()
Dim request As WebRequest = WebRequest.Create("http://192.168.8.1/api/webserver/SesTokInfo")
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Extract the header: cookie is the session id.
Dim SesStart As Short = responseFromServer.IndexOf("<SesInfo>") + 9
Dim SesEnd As Short = responseFromServer.IndexOf("</SesInfo>")
Dim TokStart As Short = responseFromServer.IndexOf("<TokInfo>") + 9
Dim TokEnd As Short = responseFromServer.IndexOf("</TokInfo>")
Dim vSessionId As String = responseFromServer.Substring(SesStart, SesEnd - SesStart)
Dim vToken As String = responseFromServer.Substring(TokStart, TokEnd - TokStart)
' Clean up the streams and the response.
reader.Close()
response.Close()
'Call SetSesAndToken(response)
'Make the api call using the session ID extracted
request = WebRequest.Create("http://192.168.8.1/api/user/login")
request.Headers.Add("__RequestVerificationToken", vToken)
request.Headers.Add("Cookie", vSessionId)
Dim PassWordEncoded As String = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin"))
Dim Myxml As String = "<?xml version:'1.0' encoding='UTF-8'?>
<request>
<Username>admin</Username>
<Password>" & PassWordEncoded & "</Password>
<password_type>4</password_type>
</request>"
Dim bytes As Byte() = Encoding.UTF8.GetBytes(Myxml)
request.Method = "POST"
request.ContentLength = bytes.Length
request.ContentType = "text/xml"
Using requestStream As Stream = request.GetRequestStream()
requestStream.Write(bytes, 0, bytes.Length)
End Using
Dim ReceiveStream As Stream
Dim encode As Encoding
Dim sr As StreamReader
Using myresponse As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
If myresponse.StatusCode <> HttpStatusCode.OK Then
Dim message As String = [String].Format("POST failed. Received HTTP {0}", myresponse.StatusCode)
Throw New ApplicationException(message)
End If
ReceiveStream = myresponse.GetResponseStream()
encode = System.Text.Encoding.GetEncoding("utf-8")
sr = New StreamReader(ReceiveStream)
responseFromServer = sr.ReadToEnd()
MsgBox(responseFromServer)
End Using
You need to have a cookie container and keep your container with the cookies for subsequent calls. You first do a GET to retreive the security token and/or other cookies then you make other calls like login etc.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim FormData As String = "login_user=&wallet=0x29a450d32a95b0b08230b93cc9ac328db81dc80e"
Dim cookiejar As New CookieContainer
Dim webreq As HttpWebRequest = HttpWebRequest.Create("https://somesite.org")
Dim responseReader As StreamReader
Dim responseData As String
Dim requestWriter As StreamWriter
webreq.Method = HttpMethod.Get.Method
webreq.CookieContainer = cookiejar
Dim xxx As HttpWebResponse = webreq.GetResponse()
responseReader = New StreamReader(webreq.GetResponse.GetResponseStream())
responseData = responseReader.ReadToEnd()
responseReader.Close()
webreq = HttpWebRequest.Create("https://somesite.org")
webreq.Accept = "text/html"
webreq.Method = HttpMethod.Post.Method
webreq.ContentType = "application/x-www-form-urlencoded"
webreq.ContentLength = FormData.Length
webreq.CookieContainer = cookiejar
requestWriter = New StreamWriter(webreq.GetRequestStream)
requestWriter.Write(FormData)
requestWriter.Close()
responseReader = New StreamReader(webreq.GetResponse.GetResponseStream())
responseData = responseReader.ReadToEnd()
responseReader.Close()
Code to Authenticate your modem:
Public Sub Main()
' Hitting the starting page
Dim cookiejar As New CookieContainer
Dim request As WebRequest = WebRequest.Create("http://192.168.8.1/api/user/state-login")
request.CookieContainer = cookiejar
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Extract the header: cookie is the session id.
' Dim SesStart As Short = responseFromServer.IndexOf("<SesInfo>") + 9
' Dim SesEnd As Short = responseFromServer.IndexOf("</SesInfo>")
' Dim TokStart As Short = responseFromServer.IndexOf("<TokInfo>") + 9
' Dim TokEnd As Short = responseFromServer.IndexOf("</TokInfo>")
' Dim vSessionId As String = responseFromServer.Substring(SesStart, SesEnd - SesStart)
' Dim vToken As String = responseFromServer.Substring(TokStart, TokEnd - TokStart)
' Clean up the streams and the response.
reader.Close()
response.Close()
' Hitting the login api endpoint
'Call SetSesAndToken(response)
'Make the api call using the session ID extracted
request = WebRequest.Create("http://192.168.8.1/api/user/login")
request.CookieContainer = cookiejar
Dim PassWordEncoded As String = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin"))
Dim Myxml As String = "<?xml version:'1.0' encoding='UTF-8'?>
<request>
<Username>admin</Username>
<Password>" & PassWordEncoded & "</Password>
<password_type>4</password_type>
</request>"
Dim bytes As Byte() = Encoding.UTF8.GetBytes(Myxml)
request.Method = "POST"
request.ContentLength = bytes.Length
request.ContentType = "text/xml"
Using requestStream As Stream = request.GetRequestStream()
requestStream.Write(bytes, 0, bytes.Length)
End Using
Dim ReceiveStream As Stream
Dim encode As Encoding
Dim sr As StreamReader
Using myresponse As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
If myresponse.StatusCode <> HttpStatusCode.OK Then
Dim message As String = [String].Format("POST failed. Received HTTP {0}", myresponse.StatusCode)
Throw New ApplicationException(message)
End If
ReceiveStream = myresponse.GetResponseStream()
encode = System.Text.Encoding.GetEncoding("utf-8")
sr = New StreamReader(ReceiveStream)
responseFromServer = sr.ReadToEnd()
MsgBox(responseFromServer)
End Using
void SaveUrl(string sourceURL, string savepath) {
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceURL);
webRequest.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string sResponseHTML = responseReader.ReadToEnd();
using (StreamWriter sw = new StreamWriter(savepath, false)) {
sw.Write(sResponseHTML);
}
string[] ImageUrl = GetImgLinks(sResponseHTML);
foreach (string imagelink in ImageUrl) {
HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(imagelink);
imgRequest.CookieContainer = cookies;
HttpWebResponse imgresponse = (HttpWebResponse)imgRequest.GetResponse();
//Code to save image
}
}
Test it out I am not a .net guy. Good Luck!
The cleaner approach is to create a Session for HTTP requests instead of hitting individual api endpoints. In this case the cookies will be sent by default.If you have enough time you can explore AT commands also. Good luck!
Code to Authenticate your modem:
Public Sub Main()
' Hitting the starting page
Dim cookiejar As New CookieContainer
Dim request As WebRequest = WebRequest.Create("http://192.168.8.1/api/user/state-login")
request.CookieContainer = cookiejar
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Extract the header: cookie is the session id.
' Dim SesStart As Short = responseFromServer.IndexOf("<SesInfo>") + 9
' Dim SesEnd As Short = responseFromServer.IndexOf("</SesInfo>")
' Dim TokStart As Short = responseFromServer.IndexOf("<TokInfo>") + 9
' Dim TokEnd As Short = responseFromServer.IndexOf("</TokInfo>")
' Dim vSessionId As String = responseFromServer.Substring(SesStart, SesEnd - SesStart)
' Dim vToken As String = responseFromServer.Substring(TokStart, TokEnd - TokStart)
' Clean up the streams and the response.
reader.Close()
response.Close()
' Hitting the login api endpoint
'Call SetSesAndToken(response)
'Make the api call using the session ID extracted
request = WebRequest.Create("http://192.168.8.1/api/user/login")
request.CookieContainer = cookiejar
Dim PassWordEncoded As String = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin"))
Dim Myxml As String = "<?xml version:'1.0' encoding='UTF-8'?>
<request>
<Username>admin</Username>
<Password>" & PassWordEncoded & "</Password>
<password_type>4</password_type>
</request>"
Dim bytes As Byte() = Encoding.UTF8.GetBytes(Myxml)
request.Method = "POST"
request.ContentLength = bytes.Length
request.ContentType = "text/xml"
Using requestStream As Stream = request.GetRequestStream()
requestStream.Write(bytes, 0, bytes.Length)
End Using
Dim ReceiveStream As Stream
Dim encode As Encoding
Dim sr As StreamReader
Using myresponse As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
If myresponse.StatusCode <> HttpStatusCode.OK Then
Dim message As String = [String].Format("POST failed. Received HTTP {0}", myresponse.StatusCode)
Throw New ApplicationException(message)
End If
ReceiveStream = myresponse.GetResponseStream()
encode = System.Text.Encoding.GetEncoding("utf-8")
sr = New StreamReader(ReceiveStream)
responseFromServer = sr.ReadToEnd()
MsgBox(responseFromServer)
End Using
void SaveUrl(string sourceURL, string savepath) {
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceURL);
webRequest.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string sResponseHTML = responseReader.ReadToEnd();
using (StreamWriter sw = new StreamWriter(savepath, false)) {
sw.Write(sResponseHTML);
}
string[] ImageUrl = GetImgLinks(sResponseHTML);
foreach (string imagelink in ImageUrl) {
HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(imagelink);
imgRequest.CookieContainer = cookies;
HttpWebResponse imgresponse = (HttpWebResponse)imgRequest.GetResponse();
//Code to save image
}
}
Please test it out I am not a .net guy. Good Luck!

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.