VB.NET posting with custom headers - vb.net

heya I'm required to post a json string to the server but I keep getting the error
The underlying connection was closed: An unexpected error occurred on a send.
I've tried adding these two codes after researching but still got the same error, any ideas?
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
this is my full code, thePostData is a JsonConvert.SerializeObject(Dictionary) String
Public Function PostToServer(thePostData As String, theConcatted As String, theNonce As String, theTimeStamp As String, theUri as Uri)
Try
'ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
Dim theRequest As HttpWebRequest = HttpWebRequest.Create(theUri)
Dim theByteArray As Byte() = Encoding.UTF8.GetBytes(thePostData)
theRequest.Method = "POST"
theRequest.ContentType = "application/json"
theRequest.Headers.Add("X-Authentication-Version", "1.1")
theRequest.Headers.Add("X-Authentication-Method", "SHA256WithRSA")
theRequest.Headers.Add("X-Authentication-KeyId", theKeyId)
theRequest.Headers.Add("X-Authentication-Nonce", theNonce)
theRequest.Headers.Add("X-Authentication-Timestamp", theTimeStamp)
theRequest.Headers.Add("X-Authentication-Sign", getDataSignature(theConcatted))
theRequest.ContentLength = theByteArray.Length
Dim theDataStream As Stream = theRequest.GetRequestStream()
theDataStream.Write(theByteArray, 0, theByteArray.Length)
theDataStream.Close()
Return True
Catch ex As Exception
Console.WriteLine(ex.Message)
Return False
End Try
End Function
Function getDataSignature(theData As String)
Dim theRSA As New RSACryptoServiceProvider
theRSA.FromXmlString(thePrivateKey)
Dim theRSAFormatter As New RSAPKCS1SignatureFormatter(theRSA)
theRSAFormatter.SetHashAlgorithm("SHA256")
Dim theSHhash As New SHA256Managed()
Dim theSignedHashValue As Byte() = theRSAFormatter.CreateSignature(theSHhash.ComputeHash(New UnicodeEncoding().GetBytes(theData)))
Dim theStringBuilder As New StringBuilder(theSignedHashValue.Length * 2)
For Each b As Byte In theSignedHashValue
theStringBuilder.Append(Conversion.Hex(b))
Next
Return theStringBuilder.ToString().ToLower()
End Function

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.NET ~ PUT WebRequest raising exceptions when trying to GetResponse of it

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

How do I know the encoding of a webpage that I read in with vb.net?

I tried reading a webpage into my program using vb.net's HttpWebRequest. My problem has to do with figuring out the encoding of the web page before I actually read it into a string. When I read it in, some characters appear as diamonds with question-marks inside the diamonds. The web page itself looks fine in a browser, its just when I read it in that some characters aren't encoded right.
The original code I used was:
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri)
Dim myWebResponse As httpWebResponse = myWebRequest.GetResponse()
Then to try to get the encoding. I used:
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
But both 'contentType' and 'charset' end up with the value 'text/html'. What I want to know is if the webpage is encoded in 'utf-8' or some other character set, so I can later retrieve it like this:
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
So to sum up, there seems to be no way to inquire what the encoding is, and then use the answer to read the webpage the right way.
Is that true? Any help is appreciated.
The entire code of the routine (asked for by a commenter) follows:
Public Shared Function DownloadFileUsingURL(ByVal URLstring As String, ByVal descFilePathAndName As String, ByRef errorMessage As String, ByRef hadRedirect As Boolean,
ByRef newURL As String, ByRef isSecureConnection As Boolean, ByVal didSupplyfullfilename As Boolean, ByRef downloadedcontent As String,
ByRef httpTohttps As Boolean, ByRef httpsTohttp As Boolean, ByRef BytesRead As Integer) As Boolean
Dim ourUri As New Uri(URLstring)
Dim csh As New ClassSyncHttp
Dim expectSecureConnection As Boolean
Dim domainchanged As Boolean
newURL = ""
errorMessage = ""
hadRedirect = False
httpTohttps = False
httpsTohttp = False
isSecureConnection = False
If URLstring.ToLower.StartsWith("https:") Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = True
Else
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = False
End If
Try
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri) ' I changed webrequest to httpwebrequest
Dim cookieContainer As CookieContainer = New CookieContainer ' needs httpwebrequest to work
myWebRequest.CookieContainer = cookieContainer
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
myWebRequest.UserAgent = "BrowseNet"
myWebRequest.Timeout = ClassGlobalVariables.downloadTimeoutMilliseconds
myWebRequest.Credentials = CredentialCache.DefaultCredentials
Dim myWebResponse As HttpWebResponse = myWebRequest.GetResponse()
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
If Not ourUri.Equals(myWebResponse.ResponseUri) Then
newURL = myWebResponse.ResponseUri.ToString
hadRedirect = True
If newURL.ToLower.StartsWith("https") Then
isSecureConnection = True
End If
compareURLs(URLstring, newURL, httpTohttps, domainchanged)
End If
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
If didSupplyfullfilename Then
Using fs As FileStream = File.Create(descFilePathAndName)
receiveStream.CopyTo(fs)
BytesRead = fs.Length
End Using
Else
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
' receiveStream.Seek(0, SeekOrigin.Begin)
downloadedcontent = reader.ReadToEnd()
BytesRead = downloadedcontent.Length
End Using
End If
myWebResponse.Close()
If expectSecureConnection Then
isSecureConnection = True
Else
isSecureConnection = False
End If
Return True
Catch ex As webException
If expectSecureConnection Then
' guessing here that the problem was that was wrong about secure connection. (Problem could be elsewhere, of course)
isSecureConnection = False
httpsTohttp = True
If ex.HResult = System.Net.WebExceptionStatus.SecureChannelFailure Then
' not sure what to do
End If
'Else
' isSecureConnection = True
End If
errorMessage = ex.Message
Return False
End Try
End Function

How to send raw json data to put method in vb.net?

i am try send raw data into PUT method , but i am getting error as "The remote server returned an error: (502) Bad Gateway"
But same data i try to use in Postman Agent, its working.
What i tried
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
req.Headers.Add("x-api-key:xxxxxY0tZN55jbXnY05Oxxxxx")
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Calling function
Dim postdata As String = "[{barcod:A0000041},{barcode:A0000113}]"
Dim data = Encoding.UTF8.GetBytes(postdata)
Dim Uri As New Uri("https://sample.com/xxxxx/xxxxx?funcName=UpdateBaarcode")
Dim result_post = SendRequest(Uri, data, "text/plain", "PUT")
What i missing , pls reply.
Regards,
Aravind
For REST API
I use WebRequest using DirectCast.
It's been so long I can't remember why. TT
Try like the code below.
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As HttpWebRequest= DirectCast(WebRequest.Create(uri), HttpWebRequest)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
req.Headers.Add("x-api-key:xxxxxY0tZN55jbXnY05Oxxxxx")
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = DirectCast(req.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function

The remote server returned an error: (502) Bad Gateway while bypassing proxy

I am trying to bypass proxy using below code... But it is showing me error i.e. ("The remote server returned an error: (502) Bad Gateway."). In inner exception i found error ("The proxy could not connect to the destination in time"). I searched a lot on internet but didnt get solution.
Here's my code for bypassing proxy...
Function ConnectViaHTTPProxy() As TcpClient
Dim SOCKET1 As System.Net.Sockets.Socket
Try
Dim request As HttpWebRequest = WebRequest.Create("Web Address--10.10.10.10")
Dim cred As String = "ProxyServer:Port--http://10.10.10.10:1010/"
Dim webProxy = New WebProxy(cred)
request.UseDefaultCredentials = True
request.Proxy = webProxy
request.Timeout = 3600 * 1000
request.ReadWriteTimeout = 3600 * 1000
request.Method = "CONNECT"
Dim credentials = New NetworkCredential("UserName", "Password", "Domain_Name")
webProxy.Credentials = credentials
Dim response = request.GetResponse()
Dim responseStream = response.GetResponseStream()
Debug.Assert(responseStream IsNot Nothing)
Const Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance
Dim rsType = responseStream.[GetType]()
Dim connectionProperty = rsType.GetProperty("Connection", Flags)
Dim connection = connectionProperty.GetValue(responseStream, Nothing)
Dim connectionType = connection.[GetType]()
Dim networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags)
Dim networkStream = networkStreamProperty.GetValue(connection, Nothing)
Dim nsType = networkStream.[GetType]()
Dim socketProperty = nsType.GetProperty("Socket", Flags)
Dim socket = DirectCast(socketProperty.GetValue(networkStream, Nothing), Socket)
SOCKET1 = socket
SOCKET1.ReceiveTimeout = 0
SOCKET1.SendTimeout = 0
Return (New TcpClient() With {.Client = SOCKET1})
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
Dim resp As WebResponse = ex.Response
Using sr As New StreamReader(resp.GetResponseStream())
FileWrite(lERROR, sr.ReadToEnd().ToString(), 0)
End Using
End If
'FileWrite(lERROR, ex.InnerException.ToString(), 0)
End Try
End Function
Can you please tell me where i am wrong....