0

我有一个要求,打印 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 复制到一个临时变量中并尝试进一步使用它,但这也不起作用。有什么建议么?

4

1 回答 1

0

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

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("\r\nResponse stream received.");
            Char[] read = new Char[256];
            // Reads 256 characters at a time.     
            int count = readStream.Read( read, 0, 256 );
            Console.WriteLine("HTML...\r\n");
            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 希望这会有所帮助!

于 2013-11-06T05:08:20.077 回答