C # - How to read continuous XML stream over HTTP

I am trying to find a better way to use a continuous stream of XML data from a service that sends data as a "persistent" channel through HTTP.

I have been considering using HttpWebRequest / Response, but I'm not sure how this will behave if the data just flows continuously.

Any thoughts?

+7
source share
2 answers

I did this before, not with XML, but with data that needs to be parsed for state changes for the application. The HttpWebResponse.GetResponseStream () method did a great job of this. Be sure to call Close () on this thread when done. I suggest a finally block.

HttpWebRequest req; try { req = (HttpWebRequest)WebRequest.Create("http://www.example.com"); Stream stream = req.GetResponseStream(); byte[] data = new byte[4096]; int read; while ((read = data.Read(data, 0, data.Length)) > 0) { Process(data, read); } } finally { if (req != null) req.Close(); } 

Or alternatively:

 HttpWebRequest req; try { req = (HttpWebRequest)WebRequest.Create("http://www.example.com"); Stream stream = req.GetResponseStream(); XmlTextReader reader = new XmlTextReader(stream); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.Write("<{0}>", reader.Name); break; case XmlNodeType.Text: Console.Write(reader.Value); break; case XmlNodeType.CDATA: Console.Write("<![CDATA[{0}]]>", reader.Value); break; case XmlNodeType.ProcessingInstruction: Console.Write("<?{0} {1}?>", reader.Name, reader.Value); break; case XmlNodeType.Comment: Console.Write("<!--{0}-->", reader.Value); break; case XmlNodeType.XmlDeclaration: Console.Write("<?xml version='1.0'?>"); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value); break; case XmlNodeType.EntityReference: Console.Write(reader.Name); break; case XmlNodeType.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (req != null) req.Close(); } 
+9
source

It should be easy enough. You will need to get the response stream by calling Response.GetResponseStream (), and then use async ResponseStream.BeginRead () in a loop.

There is no Timeout parameter in the response, but if you are sending data sequentially, this should be fine.

+2
source

All Articles