MCR
MCR

Reputation: 1643

Invalid Data HttpWebResponse from HttpWebRequest C#

I am trying to load an HttpWebResponse into an XmlDocument and am getting the exception "Data at the root level is invalid. Line 1, position 1". If I output the response to the Console I get "system.net.connectstream". The credentials don't seem to be my problem because if I enter an incorrect password my exception changes to the 404 error. Here is my code...

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

Thanks!

Upvotes: 1

Views: 1177

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503290

Calling ToString on GetResponseStream() isn't going to do much for you - Stream.ToString isn't overridden.

I suggest you use something like this for debugging::

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

Then replace the middle section (with StreamReader) with the XmlDocument.Load call.

I suspect you'll see that it's basically invalid XML, but the above should show you what it really is.

EDIT: Your comment shows the data as:

{"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"}

That's JSON. It's not XML. Don't try to load it as XML. You have two options:

  • Change what you're requesting so that you get an XML response back, if the server supports it
  • Parse it as JSON (e.g. with Json.NET) instead of as XML.

Upvotes: 2

Related Questions