Connect to WebRequest Server - vb.net

I'm trying to connect to TNT's server for making XML request.
First I'm trying to just make a successful connection (before trying to send anything).
According to TNT everything is set up ok. So I'm thinking it's on my end.
I'm using the code below. But it just comes back with, that it's unauthorized.
Dim request As WebRequest = WebRequest.Create("https://express.tnt.com/expressconnect/track.do?version=3")
Dim authInfo As String = ("username" + (":" + "password"))
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo))
request.Headers("Authorization") = ("Basic " + authInfo)
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"
Try
Dim response As WebResponse = request.GetResponse
Console.Write(response)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
Can anyone help or shed any light on what i am doing wrong?

Related

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

Visual basic HttpWebRequest getting SendFailure error

I have tried many of the recommendations here and am still getting SendFailure error.
Here is the code - it's straight forward web request
Dim request As HttpWebRequest
Dim webAddress As String = "https://www.google.com"
'webAddress = "https://www.yahoo.com"
ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls
ServicePointManager.ServerCertificateValidationCallback = _
New RemoteCertificateValidationCallback(AddressOf AcceptAllCertifications)
request = DirectCast(WebRequest.Create(webAddress), HttpWebRequest)
request.ReadWriteTimeout = 5500
request.Timeout = 5500
request.KeepAlive = False
request.Method = "GET"
Using response = request.GetResponse()
sr = New StreamReader(response.GetResponseStream())
activated = sr.ReadToEnd()
Console.WriteLine("activated says: " + activated)
resp = Split(activated, ",")
sr.Close()
response.Close()
End Using
For the google request, I get the page content in the 'activate' var, and I get a visit hit in the certificate callback function.
For the yahoo request I get an immediate WebException Status 4: SendFailure. There is no hit on the certificate callback function.
Why is this happening? I can not figure it out. I am using VisualStudio 2010.

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?

Error Handling with HTTPWebRequests, VB.NET

I've looked around and couldn't find an answer so I thought i'd ask it here.
I have a program the calls an API with login info passed in the header and the server returns some info upon authentication. The problem is if the user creds are incorrect, the program crashes and throws an exception. The error is 401. How do it catch this, and tell the user?
My code is:
Dim request = TryCast(System.Net.WebRequest.Create("https://myurl.com"), System.Net.HttpWebRequest)
request.Method = "GET"
request.Headers.Add("authorization", "Bearer " + AccessToken)
request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
MessageBox.Show(responseContent)
End Using
End Using
Thanks.
Use a try catch statement
try
'My error prone code
catch ex as Exception
'Handle my error
end try
Try
Dim request = TryCast(System.Net.WebRequest.Create("https://myurl.com"), System.Net.HttpWebRequest)
request.Method = "GET"
request.Headers.Add("authorization", "Bearer " + AccessToken)
request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
MessageBox.Show(responseContent)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

How to stop WebRequest use last successful credential - reset CredentialCache

When using the following code, if I specify a wrong username/password combination I get a 407 error.
If I use a correct one, I get the page requested.
If I try again with a wrong username/password I get a normal response.
For some reason, WebRequest caches the proxy's username/password (CredentialCache) combination for the requested URL. If I change the URL pointing to a different domain, I get a proper 407.
How can I stop WebRequest from using last successful credential?
Dim request As WebRequest = WebRequest.Create("http://contoso.com")
request.Proxy = New WebProxy("http://myproxy:8080")
Dim username = InputBox("Username")
Dim password = InputBox("Password")
request.Proxy.Credentials = New NetworkCredential(username, password)
Try
Using response = request.GetResponse()
' Display the status.
txt_response.Text = CType(response, HttpWebResponse).StatusDescription & "Response is from cache?: " & response.IsFromCache
' Get the stream containing content returned by the server.
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()
' Display the content.
txt_Result.Text = responseFromServer
' Clean up the streams and the response.
reader.Close()
response.Close()
End Using
Catch ex As WebException
txt_response.Text = ex.Status & ": " & ex.Message
End Try