I am having an issue with some code that does a HttpWebRequest to get a response back from a URL. The code does work... some times. Most of the time is gets the response back just fine. But on occasion I get the following error:
System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Any ideas?? I had read something about setting the HttpWebRequest's 'KeepAlive' property to False, which I did, but it has not permanently solved the problem.
Here is the code:
'Create an HttpWebRequest object setting the URL to postDim request As HttpWebRequest = CType(WebRequest.Create("https://www.test.com/ws/blahblahblah"), HttpWebRequest)
'Set the 'Method' property of the 'Webrequest' to 'POST'.
request.Method =
"POST"
'Create a new string with information to POST data to the Url.Dim postData As String = "id=" & Trim(ID) & "&sid=" & Trim(SID)
'Store data in a byte array using ASCII standardDim byte1 As Byte() = Encoding.ASCII.GetBytes(postData)
'Set the content type of the data being posted.
request.ContentType =
"application/x-www-form-urlencoded"
'Set the content length of the string being posted.
request.ContentLength = byte1.Length
'Setting KeepAlive = false results in sending a Connection: Close header to the server.
request.KeepAlive =
False
'Send the request;
'When using the POST method, you must get the request stream, write the data to be posted, and close the stream. Dim newStream As Stream = request.GetRequestStream()
newStream.Write(byte1, 0, byte1.Length)
newStream.Close()
'Get the HTTP response, casting to a type of HttpWebResponseDim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
'Load the HTTP response into a StreamReader objectDim sr As New StreamReader(response.GetResponseStream, UTF8)
'Read the stream returned from the response objectDim HTMLResponse As String = Trim(sr.ReadToEnd())
'Based on the response, define the boolean variable dictating if the user is valid
If CStr(Replace(HTMLResponse, vbCrLf, "")) = "Y" Then
User =
True
Else
User =
False
End If
'Close the response object and StreamWriter (IMPORTANT)
response.Close()
sr.Close()