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

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

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)

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?

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!

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 ?

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.