来自 HttpWebResponse 的 XML 字符串和对象模型转换



我有一个要求,打印XML字符串以及从HttpResponse转换对象模型。我为此编写了以下代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse tmpResponse = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Copying the response
//tmpResponse = response;
//Response to XML string
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    sResult = sr.ReadToEnd();
}
//Reponse to  Object model
objectmodel = convert(response);

问题是,如果我在两者之间将响应转换为 XML 字符串,则代码在对象模型转换时会遇到错误。错误是:

 There is an error in XML document (0, 0). ---> System.Xml.XmlException: Root element is missing.

实现这一点的更好方法是什么?我也尝试将 HttpResponse 复制到临时变量中并尝试进一步使用它,但这也不起作用。有什么建议吗?

我认为你的字符串是空的,这就是你得到 XmlException 的原因。尝试打印响应,看看这是否为 != 空。你也不应该解码响应吗?

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
            // Sends the HttpWebRequest and waits for the response.         
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
            // Gets the stream associated with the response.
            Stream receiveStream = myHttpWebResponse.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader( receiveStream, encode );
        Console.WriteLine("rnResponse stream received.");
            Char[] read = new Char[256];
            // Reads 256 characters at a time.     
            int count = readStream.Read( read, 0, 256 );
            Console.WriteLine("HTML...rn");
            while (count > 0) 
                {
                    // Dumps the 256 characters on a string and displays the string to the console.
                    String str = new String(read, 0, count);
                    Console.Write(str);
                    count = readStream.Read(read, 0, 256);
                }
            Console.WriteLine("");
            // Releases the resources of the response.
            myHttpWebResponse.Close();
            // Releases the resources of the Stream.
            readStream.Close();

另请结帐 : http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx希望这有帮助!

最新更新