WebRequest and Unable to read data from the transport connection Error

Tuesday, June 30th, 2009 | Code

Weird thing just happened, a Windows Service responsible for grabbing some data form an online XML source, suddenly stopped working after two years of continuous functioning…

First I thought that the remote XML had changed somehow but the service returned
“Unable to read data from the transport connection: The connection was closed.”

The code that connected to the remote XML was pretty low-tech:

WebRequest wRq = WebRequest.Create(remoteUri);
WebResponse wRs = wRq.GetResponse();
Stream strm = wRs.GetResponseStream();
StreamReader sr = new StreamReader(strm, Encoding.UTF7);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(strm);
//IT WAS CRASHING HERE

After some research it seems that the remote side closes the connection prior to it being finished…
I had to change the code as follows and the problem was solved:


CookieContainer CC = new CookieContainer();
HttpWebRequest wRq = (HttpWebRequest)WebRequest.Create(remoteUri);
wRq.Proxy = null;
wRq.UseDefaultCredentials = true;
wRq.KeepAlive = false; //THIS DOES THE TRICK
wRq.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
wRq.CookieContainer = CC;
WebResponse wRs = wRq.GetResponse();
Stream strm = wRs.GetResponseStream();
StreamReader sr = new StreamReader(strm, Encoding.UTF7);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(strm);
//NO LONGER CRASHING HERE