1

我正在尝试将 HttpWebResponse 加载到 XmlDocument 中,并收到异常“根级别的数据无效。第 1 行,位置 1”。如果我将响应输出到控制台,我会得到“system.net.connectstream”。凭据似乎不是我的问题,因为如果我输入了错误的密码,我的异常会更改为 404 错误。这是我的代码...

string username = "username";
string password = "password";
string url = "https://myurl.com";

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(username, password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
Console.WriteLine(response.GetResponseStream());
xmlDoc.Load(response.GetResponseStream());

谢谢!

4

1 回答 1

2

调用不会对您有太大帮助 -ToString不会被覆盖。GetResponseStream()Stream.ToString

我建议你使用这样的东西进行调试::

// Prefer casting over "as" unless you're going to check it...
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        // For diagnostics, let's assume UTF-8
        using (StreamReader reader = new StreamReader(stream))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}

(with StreamReader)然后用XmlDocument.Load调用替换中间部分。

我怀疑你会看到它基本上是无效的 XML,但上面应该向你展示它的真正含义。

编辑:您的评论将数据显示为:

{"messages":{"message":"1 Device(s) returned."},"devices":{"device":
    {"@id":"00","uuid":"00000000","phonenumber":"000‌​000",
     "user name":"0000","name":"Guy,Somebody","platform":"platform","os":"III",
     "version":"1‌​.1.1"}},"appName":"someApp"}

那是JSON。它不是 XML。不要尝试将其加载为 XML。你有两个选择:

  • 如果服务器支持,请更改您请求的内容,以便获得 XML 响应
  • 将其解析为 JSON(例如使用Json.NET)而不是 XML。
于 2012-08-02T13:27:49.773 回答