C# Won't Load A Certain XML, But Works in Browser

前端 未结 1 579
我寻月下人不归
我寻月下人不归 2020-12-12 02:35

I\'m new(er) to C#, but I have a background with Java and VB.NET, so jumping in was easy. This weekend I started a new mini-project with C# and a public XML feed from the in

相关标签:
1条回答
  • 2020-12-12 03:07

    As i indicated in my comment, XmlDocument.Load is farely primitive compared to a full blown request from a browser. When you use a proxy- or packet tracer like Fiddler, you will find that for example IE9 makes a request including specific headers:

    GET http://stats.us.playstation.com/warhawk/XmlFeedAction.action?start=1&end=1 HTTP/1.1 Accept: text/html, application/xhtml+xml, / Accept-Language: en-US User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) Accept-Encoding: gzip, deflate Connection: Keep-Alive Host: stats.us.playstation.com Cookie: JSESSIONID=HLygTblTG13HhXqqw80jw9Wdhw0q03dxcQLp04fD3Q5yChYvPGn6!-882698034; SONYCOOKIE1=543467712.20480.0000

    Now the webserver's behavior is subjected to the headers specified in a request. In this case, the Accept and user-agent play a role. I can succesfully load the xml content in a XmlDocument by including some fake headers like the following:

            string url = "http://stats.us.playstation.com/warhawk/XmlFeedAction.action?start=1&end=1";
    
            WebClient client = new WebClient();
            client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";
            client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            string data = client.DownloadString(url);
    
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(data);
    
    0 讨论(0)
提交回复
热议问题