2012-08-02 73 views
1

我想加載一個HttpWebResponse到一個XmlDocument,並得到異常「根數據無效。行1,位置1」。如果我輸出響應到控制檯,我會得到「system.net.connectstream」。憑據似乎不是我的問題,因爲如果我輸入一個不正確的密碼,我的異常更改爲404錯誤。這裏是我的代碼...來自HttpWebRequest的無效數據HttpWebResponse C#

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()); 

謝謝!

回答

2

GetResponseStream()上調用ToString不會爲您做很多 - 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()); 
     } 
    } 
} 

然後與XmlDocument.Load調用替換中段(with StreamReader)

我懷疑你會發現它基本上是無效的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。
+0

StreamReader允許我抓取數據並看到我正在獲取正確的數據,但是當我將XMLDocument.Load放回時,我得到相同的錯誤。這裏是流的樣子(刪除了數據)... – MCR 2012-08-02 14:04:35

+0

{「messages」:{「message」:「1 devices(s)returned。」},「devices」:{「device」:{「@ id 「:」00「,」uuid「:」00000000「,」phonenumber「:」000000「,」用戶名「:」0000「,」姓名「:」Guy,Somebody「,」platform「 os「:」III「,」version「:」1.1.1「}},」appName「:」someApp「} – MCR 2012-08-02 14:05:52

+0

@MCR:好的,這是JSON,不是XML ... – 2012-08-02 14:07:21

相關問題