0

I want to send a Post request from the server side to another server. I want to create some form data in the code (not using a webpage) and send it over.

From what I have read online I have ended up with the code below. However, I am just guessing and not sure if it is correct, especially because I cannot get it to work (the exception I am getting has been included as a comment in the code). Is this a fault on my part or is it an external problem to do with where I am sending the request?

Dim client = New HttpClient

Dim request = WebRequest.CreateHttp("https://something.com/test")
request.Credentials = CredentialCache.DefaultCredentials
request.UserAgent = "value"
request.Method = HttpMethod.Post.Method
request.ContentType = "application/x-www-form-urlencoded"

Dim params = New Dictionary(Of String, String)
params.Add("key1", "value1")
params.Add("key2", "value2")
params.Add("key3", "value3")
params.Add("key4", "value4")

Dim stream = request.GetRequestStream()
Dim content = New FormUrlEncodedContent(params)
content.CopyToAsync(stream)

' Exception occurs when executing the line below:           
' The underlying connection was closed: An unexpected error occurred on a send.
' InnerException = {"Unable to read data from the transport connection: 
' An existing connection was forcibly closed by the remote host."}  

Dim result = request.GetResponseAsync().Result          

Console.WriteLine(result.ToString)
Mayron
  • 2,146
  • 4
  • 25
  • 51

1 Answers1

0

Are you sure that the server has a valid https certificate?

  1. The cert was issued to the URI that you are hitting
  2. The cert is not expired
  3. The cert was issued by a trusted authority (e.g.: Verisign)

Of these criteria, #3 is the most commonly failed check. You can programatically ignore any or all of these errors (at your own risk). Here is an example on how to do that. (Reference: https://stackoverflow.com/a/10390388/8081260)

Also it would be helpful to provide the full (inner) exception

  • Okay thank you. That was the inner exception (in the code comment). It is very basic. The stacktrace shows more but I think you are correct that the URL is causing an issue, maybe on the other server side (such as a firewall issue). I was mainly concerned that it could be my problem because I have never used HttpClient / WebRequest. – Mayron May 30 '17 at 08:53