Having problems with httpost json string through vb.net - vb.net

Here's my code that I am using to send as post to the specified URL.
Dim url = "http://www.abc.com/new/process"
Dim data As String = nvc.ToString
Dim postAddress = New Uri(Url)
Dim request = DirectCast(WebRequest.Create(postAddress), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/json"
Dim postByteData As Byte() = UTF8Encoding.UTF8.GetBytes(data)
request.ContentLength = postByteData.Length
Using postStream As Stream = request.GetRequestStream()
postStream.Write(postByteData, 0, postByteData.Length)
End Using
Using resp = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader = New StreamReader(resp.GetResponseStream())
result.Response = reader.ReadToEnd()
End Using
Now the problem is I don't get any exception here, but the response I'm supposed to get after posting (success or error) is not coming to my end. The URL is fine, I checked it. Am I sending it the right way?

I believe the issue is that ReadToEnd method on StreamReader internally uses the Length property. This will be null if the server doesn't send a length in the http header. Try using memory stream and a buffer instead:
Dim url = "http://my.posturl.com"
Dim data As String = nvc.ToString()
Dim postAddress = New Uri(url)
Dim request As HttpWebRequest = WebRequest.Create(postAddress)
request.Method = "POST"
request.ContentType = "application/json"
Dim postByteData As Byte() = UTF8Encoding.UTF8.GetBytes(data)
request.ContentLength = postByteData.Length
Using postStream As Stream = request.GetRequestStream()
postStream.Write(postByteData, 0, postByteData.Length)
End Using
Using resp = TryCast(request.GetResponse(), HttpWebResponse)
Dim b As Byte() = Nothing
Using stream As Stream = resp.GetResponseStream()
Using ms As New MemoryStream()
Dim count As Integer = 0
Do
Dim buf As Byte() = New Byte(1023) {}
count = stream.Read(buf, 0, 1024)
ms.Write(buf, 0, count)
Loop While stream.CanRead AndAlso count > 0
b = ms.ToArray()
End Using
End Using
Console.WriteLine("Response: " + Encoding.UTF8.GetString(b))
Console.ReadLine()
End Using

Related

Reading Rest API Call Response Status Code in VB.NET

I am a beginner in the API ecosystem. I am using VB.NET to call API. Code used for the same given below:
Try
Dim s As HttpWebRequest
Dim enc As UTF8Encoding
Dim postdata As String
Dim postdatabytes As Byte()
Dim jo As New JObject
jo.Add("apiid", objProp.Text7)
jo.Add("apiData", objProp.Text8)
postdata = jo.ToString()
s = HttpWebRequest.Create(objProp.Text6)
enc = New System.Text.UTF8Encoding()
postdatabytes = enc.GetBytes(postdata)
s.Method = "POST"
s.ContentType = "application/json"
s.ContentLength = postdatabytes.Length
s.Headers.Add("user-name", "MjRKQGU1NypQJkxZYVpCdzJZXnpKVENmIXFGQyN6XkI=")
s.Headers.Add("api-key", "UjMhTDZiUlE1MkhMWmM2RkclJXJhWUJTTWZDeHVEeDQ=")
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result = s.GetResponse()
Dim responsedata As Stream = result.GetResponseStream
Dim responsereader As StreamReader = New StreamReader(responsedata)
Dim xResponse = responsereader.ReadToEnd
Try
Dim opData = JObject.Parse(xResponse)("apiData").ToString
objProp = JsonConvert.DeserializeObject(Of default_prop)(opData)
Catch ex As Exception
End Try
Catch myerror As OracleException
'Status
objProp.Text5 = "500"
'Failure Response Message
objProp.Text11 = "Internal Server Error..."
db_close()
End Try
My issue is that I could not find the proper syntax to retrieve API Response Status Code from the response. Request your guidance
With some small changes on your code you can do the trick as follow:
'....... other code here
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result As HttpWebResponse = CType(s.GetResponse(), HttpWebResponse)
Console.WriteLine(result.StatusCode)

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

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!

REST WebService: how to get zip file from web service to a client

I'm trying to create a function to download a zip file made ​​available from a REST WebService with a client that calls the Web Service(both written in VB.Net).
WebService side I have the following code:
Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
Dim length As Integer = CType(f.Length, Integer)
WebOperationContext.Current.OutgoingResponse.ContentLength = length
Dim buffer As Byte() = New Byte(length) {}
Dim sum As Integer = 0
Dim count As Integer
While ((count = f.Read(buffer, sum, length - sum)) > 0)
sum += count
End While
f.Close()
Dim mimeType = ""
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
Return New MemoryStream(buffer)
End Function
Client side I have the following code:
sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False
Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Response has ContentLenght = 242699, so seems to receive the stream, but StIn seems to be empty. What is the best solution to solve the problem?
I think you've forgot to read from the StreamReader to the file.
Dim inSaveFile As String = "C:\stream\test.doc"
If Dir(inSaveFile) <> vbNullString Then
Kill(inSaveFile)
End If
Dim swFile As System.IO.StreamWriter
Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)
Dim response1 As System.Net.HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)
swFile.WriteLine(stIn.ReadToEnd)
swFile.Close()
fs.Close()

HttpWebRequest POST and Cookies

Hi am trying to make an application that post data to a joomla login page but the only thing i get back is cookies is not enabled.
Function GetPage(ByVal Url As String) As String
Dim CookieJar As New Net.CookieContainer
Dim enc As Encoding = Encoding.GetEncoding(1252)
Dim Data As Byte() = Nothing
Dim PostData As String = ""
If InStr(Url, "?") <> 0 Then
PostData = Url.Substring(InStr(Url, "?"))
Url = Replace(Url, PostData, "")
Url = Url.TrimEnd("?"c)
Data = enc.GetBytes(PostData)
End If
Dim req As System.Net.HttpWebRequest = CType(Net.WebRequest.Create(Url), Net.HttpWebRequest)
req.AllowAutoRedirect = False
req.ContentType = "application/x-www-form-urlencoded"
req.Method = "POST"
If Not Data Is Nothing Then
If Data.Length > 0 Then
req.ContentLength = Data.Length
Dim newStream As Stream = req.GetRequestStream()
newStream.Write(Data, 0, Data.Length)
newStream.Flush()
newStream.Close()
End If
End If
req.CookieContainer = CookieJar
Dim Response As Net.HttpWebResponse = CType(req.GetResponse(), Net.HttpWebResponse)
Dim ResponseStream As IO.StreamReader = New IO.StreamReader(Response.GetResponseStream(), enc)
Dim Html As String = ResponseStream.ReadToEnd()
Response.Close()
ResponseStream.Close()
Return Html
End Function
How should i do?
Try to set .CookieContainer before writing any data to .GetRequestStream()
Look this sample:
CookieContainer cookies = new CookieContainer();
HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(site);
postRequest.CookieContainer = cookies; // note this
postRequest.Method = "POST";
postRequest.ContentType = "application/x-www-form-urlencoded";
using (Stream stream = postRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}