다음을 통해 공유


HttpWebRequest POST method Err. The underlying connection was closed

Currently I faced an issue while posting an xml file through the 3rd party web service. I used HttpWebRequest to access the web service (Rest Based), but was getting error "The underlying connection was closed: An unexpected error occurred on a send."

I used the fiddler tool to analyze the internal of request, but strange the code started working. I was happy. I stopped the Fiddler tool and went to the code and re-executed. It stopped working and gave me same error. Was there something magic done by Fiddler tool?

I was using a web application and by clicking of a button the file had to be posted. Then I found something interesting that the Fiddler tool was using a proxy. But I could not find the proxy details from the internet explorer -> tool -> settings-> Connection -> LAN Settings. But I could see option for "Use automatic configuration script" and a link https://pac.xxxxxx.net/.

The PAC (Proxy Auto Config) file defines the way bowsers use the proxy. I just clicked the link and it prompts to save the file. I saved it and opened with notepad and hurrey got the proxy details with port number. Below is the complete code to be used in the Button Click event. Once clicked, the xml file will be posted and the response (xml in my case) would be shown in a text box.

string username = "username";
string password = "Password";

HttpWebRequest req = null;
HttpWebResponse res = null;

const string url = "https://myTestLink";
req = (HttpWebRequest)WebRequest.Create(url);
String encoded = System.Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
req.Headers.Add("Authorization", "Basic " + encoded);
req.Method = "POST";
req.ContentType = "application/xml; charset=utf-8";
req.Timeout = 30000;

req.Headers.Add("SOAPAction", url);

// proxy details
req.Proxy = new WebProxy("proxy.xxx.com", 8080);
req.KeepAlive = true;

var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc.Load(@"C:\Users\test\Desktop\myTest.xml");
string sXml = xmlDoc.InnerXml;

req.ContentLength = sXml.Length;

var sw = new StreamWriter(req.GetRequestStream());
sw.Write(sXml);
sw.Close();

res = (HttpWebResponse)req.GetResponse();
Stream responseStream = res.GetResponseStream();
var streamReader = new StreamReader(responseStream);

//Read the response into an xml document
var soapResonseXmlDocument = new XmlDocument();
soapResonseXmlDocument.LoadXml(streamReader.ReadToEnd());

TextBox1.Text = soapResonseXmlDocument.InnerXml;