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."
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; {
 HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);

 webRequest.KeepAlive = false;
 webRequest.ProtocolVersion=HttpVersion.Version10;
 return webRequest;
 }
– mcamara