WebRequest Connection Error Only When Server Executing Backend Work - vb.net

I've got a VB.NET app executing a simple WebRequest that is to interact with a web API. Through testing, I can successfully have the WebRequest executed and get a server response when I'm calling any static page on the server.
But when I execute a request of the API (which is interacting with a MySQL DB) the VB.NET app always throws this error:
The underlying connection was closed: An unexpected error occurred on
a send.
I do not get that error when I execute the same URL in a browser from the same PC. The API returns JSON encoded text with a text/plain content header.
Here is the VB.NET application code:
strURL = "https://soc-server.com/wireless/soc_wapi.php?&function=add_kb_event&logtype=33&datetime=2013-12-16%2013:50:50&kid=4&pid=1&peid=5&cid=97"
Dim ReturnValue As String = String.Empty
Dim Request As HttpWebRequest = CType(WebRequest.Create(New Uri(strURL)), HttpWebRequest)
Try
Dim ResponseText As String = String.Empty
Using Response As HttpWebResponse = CType(Request.GetResponse, HttpWebResponse)
Using ReceiveStream As Stream = Response.GetResponseStream
Using ReadStream As StreamReader = New StreamReader(ReceiveStream)
ReturnValue = ReadStream.ReadToEnd
processLog(ReturnValue)
End Using
End Using
End Using
Catch ex As Exception
processError(ex, "Error sending data")
End Try

Related

How do I add grant_type, username and password to API request in VB.net

I'm trying to figure out how to get an authorization token from the BIC - BOXTECH API. I can do it in a program called POSTMAN that helps with API stuff, but I cannot work out how to take what I have in POSTMAN and code it into my VB.NET application. I believe I may need to add a BODY to my HTTPWebRequest but don't know how. Can anyone point me in the right direction. New to API's. Thx.
This is the code I have so far - but missing the way to add:
grant_type=password
username=myemail#somedomain.com
password=mypassword
Public Function GetBoxAPIToken() As String
Try
Dim request As WebRequest = HttpWebRequest.Create($"https://app.bic-boxtech.org/oauth/token")
With request
.Headers.Add("Authorization", $"Basic YmljYXBwOmJpY3NlY3JldGFwcA==")
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
End With
Using response As WebResponse = request.GetResponse()
Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim jsonResponseText As String = streamReader.ReadToEnd()
Dim m As JArray = JArray.Parse(jsonResponseText)
Console.WriteLine(m.Item(0).Item("accessToken"))
Return m.Item(0).Item("accessToken")
End Using
End Using
Catch ex As Exception
'Catch error here...
Return Nothing
End Try
End Function

error 'The given key was not present in the dictionary' when trying to API HTTP request token with Blue Prism

Im trying to use the Blue Prism object HTTP request to get an access token for further processing the items. However, i couldn't manage to get the token due to the error 'The given key was not present in the dictionary'. I have looked all parameters and still didn't manage to solve the issue. I use a built in visual basic code to get the result as a collection which is later parsed to JSON to get the token.
The underlying visual basic code is:
Dim request As WebRequest = WebRequest.Create(addressURL)
If forcePreAuth Then
'Sometimes a web server will require the authorisation header in the initial request
'In which case we have to add the basic authorization header manually.
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}",username,password))
Dim base64 As String = Convert.ToBase64String(bytes)
request.Headers.Add("Authorization", "Basic " & base64)
Else
If Not String.IsNullOrEmpty(username) AndAlso Not String.IsNullOrEmpty(password) Then
request.Credentials = New NetworkCredential(username,password)
End If
End If
If useProxy Then
Dim proxyURI As New Uri(proxyURL)
Dim proxy As New WebProxy(proxyURI, True)
Dim proxyCred As New NetworkCredential(proxyUsername, proxyPassword)
Dim credCache As New CredentialCache()
credCache.Add(proxyURI, "Basic", proxyCred)
proxy.UseDefaultCredentials = False
proxy.Credentials = credCache
request.Proxy = proxy
End If
request.Method = method
request.ContentType = contentType
Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest)
If httpRequest IsNot Nothing Then
If Not String.IsNullOrEmpty(accept) Then
httpRequest.Accept = accept
End If
If Not String.IsNullOrEmpty(certID) Then
httpRequest.ClientCertificates.Add(m_Certificates(certID))
End If
End If
For Each r As DataRow In headers.Rows
For Each c As DataColumn In headers.Columns
Dim columnName As String = c.ColumnName
Dim val As String = r(columnName).ToString
request.Headers.Add(columnName,val)
Next
Exit For 'Only one row is allowed
Next
If Not String.IsNullOrEmpty(body) Then
Dim requestStream As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(requestStream, New Text.UTF8Encoding(False))
sw.Write(body)
End Using
End If
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
End Using
Screenshots:
Input parameter
Input parameter request token
Request token:
Output parameter:
Blue Prism uses a bit of a peculiar pattern regarding Certificates. The way the Utility - HTTP object is designed is to allow for the loading of certificate files (.cer, etc) on-the-fly into a local Certificate Store, which assigns a new Certificate ID each time.
Before firing your HTTP Request, use the Load Certificate action within the same Utility - HTTP object to output a valid Certificate ID, which you can then pass to HTTP Request's Certificate ID parameter.

Problem query get to api rest with authorization bearer

I need to make a query by getting to an api rest with authorization bearer, the problem is that the vb.net code returns an error in the GetResponse.
ERRORS:
The connection is terminated: Unexpected shipping error.
IOException: Unable to write data to the transport connection: The interruption of an existing connection has been forced by the remote host.
SocketException: The interruption of an existing connection has been forced by the remote host**
I'm not sure the code is correct since I have not found very good examples on the internet ...
I would appreciate the help of someone who understands a bit more than me about the topic
Thanks for all!
Dim s As HttpWebRequest
Dim r As HttpWebResponse
Dim reader As StreamReader
s = HttpWebRequest.Create("https://xxxx.xxxx.net/api/v1/PrivilegedCustomers/byIdentity/D/04400012680")
s.Method = "GET"
s.Headers.Add("Authorization", "Bearer " & Token())
's.ContentType = "application/x-www-form-urlencoded"
r = DirectCast(s.GetResponse(), HttpWebResponse)
reader = New StreamReader(r.GetResponseStream())
Dim json_api As String = reader.ReadToEnd()
Dim json As JObject = JObject.Parse(json_api)

Having trouple uploading to virtual directory via http in vb.net

Trying to upload an image to HTTP virtual directory and I keep getting this exception:
A first chance exception of type 'System.Net.WebException' occurred in System.dll
at System.Net.HttpWebRequest.GetResponse()
Dim mFileStream As New FileStream("/Image Location/", FileMode.Open)
Dim mRequest As WebRequest = WebRequest.Create("/URL/")
mRequest.Headers.Set("filename", "new name")
mRequest.Proxy = New WebProxy("/URL/", True)
mRequest.Method = "POST"
mRequest.ContentLength = mFileStream.Length
Dim mCredentials As New NetworkCredential
mCredentials.Password = "/pass/"
mCredentials.UserName = "/Login Name/"
mRequest.Credentials = mCredentials
Dim mData(mFileStream.Length - 1) As Byte
mFileStream.Read(mData, 0, mFileStream.Length)
mFileStream.Close()
Using dataStream As Stream = mRequest.GetRequestStream()
dataStream.Write(mData, 0, mData.Length)
dataStream.Close()
End Using
Dim mResponse As HttpWebResponse = CType(mRequest.GetResponse(), HttpWebResponse)
mResponse.Close()
Upon further investigation, I have found the reason for the WebException is:
ProtocolError The remote server returned an error: (405) Method Not Allowed.
The answer was quite simple despite everything i tried
you have to specify the file name in the url
Dim mRequest As WebRequest = WebRequest.Create("/URL/")
to
Dim mRequest As WebRequest = WebRequest.Create("/URL/" & FileName & FileExtention)
ex:
Dim mRequest As WebRequest = WebRequest.Create("http://1.1.1.1/niveimage.png")

GetResponse not working for internal url

I am trying to return a webpage as a stream.
What i have got so far works when i try and access an external url i.e. 'http://www.google.com'. But when i try and access a website on our server i.e. 'http://servername/applicationname/default.aspx'.
Below is the code that i currently have, that works for external :
Dim request As HttpWebRequest = CType(WebRequest.Create("http://www.google.com/search?q=google"), HttpWebRequest)
Dim response As HttpWebResponse = CType(request.GetResponse, HttpWebResponse)
Dim resStream As Stream = response.GetResponseStream
But when i try it with this line i get The remote server returned an error: (401) Unauthorized.
Dim request As HttpWebRequest = CType(WebRequest.Create("http://Server/Application/SubFolder/testing.aspx"), HttpWebRequest)
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
I have tried altering the credentials it accesses the server with using :
request.Credentials = CredentialCache.DefaultCredentials
And i have tried using a web client :
Dim myWebClient As New WebClient()
Dim myStream As Stream = myWebClient.OpenRead("http://Server/Application/SubFolder/testing.aspx")
You're getting the 401 error because the web server's authentication is rejecting the request. You may need to explicitly set your credentials.
request.Credentials = New NetworkCredential("userName", "password", "domain")