Httpwebrequest fault

Asked

Viewed 4,507 times

4

I’m trying to consume a Webservice via Webrequest in c# and I just can’t get any response from the server. However, via Postman I get the answer using the same parameters.

code:

            var JsonCliente = JsonConvert.SerializeObject(clienteMP);
            var payload = UTF8Encoding.UTF8.GetBytes(JsonCliente);

            String username = APIKey;
            String password = "";
            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

            string URLRequest = URI;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URLRequest);
            request.Headers.Add("Authorization", "Basic " + encoded);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "application/json";

            using (var writer = new StreamWriter(request.GetRequestStream()))
            {
                var settings = new JsonSerializerSettings();

                settings.NullValueHandling = NullValueHandling.Ignore;

                var data = JsonConvert.SerializeObject(clienteMP, Newtonsoft.Json.Formatting.None, settings);
                writer.Write(data);
                writer.Flush();
                writer.Close();
            }

            WebResponse response = request.GetResponse();
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                dynamic myObject = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());
                return myObject.ToString();
            }

the Exception is given on the line WebResponse response = request.GetResponse(); , the error message is:

Innerexception = {"It was forced to cancel an existing connection by the remote host"}

Message = "Unable to read transport connection data: Forced cancellation of an existing connection by remote host."

  • 1

    I found a POST talking about this at the MSDN forum (https://social.msdn.microsoft.com/Forums/pt-BR/41d9f2f6-e163-4f6d-b226-c8ce925e1c51/erro-em-retorno-de-webservice?forum=webgeralpt), try this: protected and Webrequest Getwebrequest(Uri Uri)&#overrida; {&#xA; HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);&#xA;&#xA; webRequest.KeepAlive = false;&#xA; webRequest.ProtocolVersion=HttpVersion.Version10;&#xA; return webRequest;&#xA; }

1 answer

8


I found the solution in the comment link, the problem was security protocol, just add the following line before resquest:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  • 1

    I’m glad it worked out :)

  • 1

    Man! I was 3 days looking for a solution! Yours worked! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.