У меня есть сервис Soap, который выполняет вызовы к сторонним API.
В последнее время звонки на API начали сбой.
WebException: The underlying connection was closed: An unexpected error occurred on a send
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
SocketException: An existing connection was forcibly closed by the remote host
Код
public static Task<XDocument> PostRtt(Uri uri, string username, string password, XElement requestData)
{
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
var t1 = Task.Factory.FromAsync(req.BeginGetRequestStream, req.EndGetRequestStream, null);
using (var stream = t1.Result)
{
string xmldoc = $"<?xml version=\"1.0\"?>{requestData}";
var encxml = HttpUtility.UrlEncode(xmldoc);
string body = $"Username={username}&Password={password}&Version=2&XMLRequest={encxml}";
var buff = Encoding.UTF8.GetBytes(body);
stream.Write(buff, 0, buff.Length);
}
return Task.Factory.StartNew(() =>
{
var t2 = Task.Factory.FromAsync(req.BeginGetResponse, req.EndGetResponse, null);
using (var resp = t2.Result)
{
var wr = (HttpWebResponse)resp;
if (wr.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Bad response status code: " + wr.StatusCode);
}
using (var rs = wr.GetResponseStream())
using (var sr = new StreamReader(rs))
{
var responseXml = sr.ReadToEnd();
return XDocument.Parse(responseXml);
}
}
});
}
Я пытался
req.KeepAlive =false