Search code examples
c#httpwebrequestxmldocument

Server returning 500 error when using WebRequest to get XML document


Here is my code to get the xml document from a url that is passed in.

var request = WebRequest.Create(url);
                    request.Method = "GET";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = 0;

                    var response = request.GetResponse(); // Error is thrown here

When I copy and paste the url into my browser it works just fine.

Here is the complete xml that is returned

<Model>
   <Item>
     <Id>7908</Id>
   </Item>
</Model>

Is the xml in an incorrect format? I have tried changing the content type to be application/xml but I still get this error.

EDIT=======================================================

I am trying to use webclient using this code:

using (var wc = new System.Net.WebClient())
                {
                    wc.Headers["Method"] = "GET";
                    wc.Headers["ContentType"] = "text/xml;charset=\"utf-8\"";
                    wc.Headers["Accept"] = "text/xml, */*";
                    wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; .NET CLR 3.5.30729;)";
                    wc.Headers[HttpRequestHeader.AcceptLanguage] = "en-us";
                    wc.Headers["KeepAlive"] = "true";
                    wc.Headers["AutomaticDecompression"] = (DecompressionMethods.Deflate | DecompressionMethods.GZip).ToString();

                    var response = wc.DownloadString(url);
                }

The response string is empty!!! Any ideas why this is not returning any result but pasting the url into the browser returns the xml?


Solution

  • I finally got it working. I had to use this code:

    using (var wc = new System.Net.WebClient())
                    {
                        wc.Headers["Method"] = "GET";
                        wc.Headers["Accept"] = "application/xml";
    
                        var response = wc.DownloadString(url);
                    }
    

    The key was using the accept header of "application/xml" otherwise the response would come back empty.