我试图从API中获取信息,该API在JSON数组中返回一个结果。
这是我的密码:
string sURL = "http://api.planets.nu/games/list?limit=1";
WebRequest wrGetURL = WebRequest.Create(sURL);
StreamReader objReader = new StreamReader(wrGetURL.GetResponse().GetResponseStream());
string sLine;
sLine = objReader.ReadToEnd();
Console.WriteLine(sLine);在firefox中粘贴URL时,我得到的是纯文本:
[{"name":"Upikarium Sector","description":"This is a battle for the Upikarium Sector. This is a default configuration game. Custom map. This game has 2 turns per week.","shortdescription":"","status":2,"datecreated":"8\/28\/2011 10:11:28 PM","dateended":"1\/1\/0001 12:00:00 AM","maptype":2,"gametype":2,"wincondition":1,"difficulty":1.07299030764822,"tutorialid":0,"requiredlevelid":0,"maxlevelid":0,"masterplanetid":467,"quadrant":23,"mintenacity":0,"faststart":0,"turnsperweek":2,"yearstarted":8,"isprivate":false,"scenarioid":0,"createdby":"none","turn":229,"slots":11,"turnstatus":"xx3x_67x___","hostdays":"_M___F_","slowhostdays":"","hosttime":"18:3","lastbackuppath":"c:\\planetsdata\\backups\\game22158\\turn228-635191849885449557.zip","nexthost":"11\/8\/2013 6:03:00 PM","allturnsin":false,"lastnotified":false,"ishosting":false,"lastloadeddate":"11\/6\/2013 9:16:22 PM","deletedate":"","lasthostdate":"11\/4\/2013 6:04:49 PM","password":"","haspassword":false,"statusname":"Running","timetohost":"Next turn in 44 hours","id":22158}]
这就是我的代码应该得到的。一个数组,带有一个保存游戏信息的对象。
然而,写线的结果是一堆混乱的字符。我只是看不出恰当的文本结果。我已经为这件事绞尽脑汁了很久了,我不知道为什么。这可能与返回JSON数组有关,因为对返回JSON字典的API的get调用会产生完全可读的文本。然而,这并不是一个可读的字符串!
我很确定我错过了一些简单的东西,但这不会影响到我!
发布于 2013-11-06 22:23:11
正如它在文档中所述,内容是gziped,添加对System.IO.Compression的引用并使用以下代码:
string sURL = "http://api.planets.nu/games/list?limit=1";
HttpWebRequest wrGetURL = (HttpWebRequest)WebRequest.Create(sURL);
wrGetURL.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
StreamReader objReader = new StreamReader(wrGetURL.GetResponse().GetResponseStream(), Encoding.UTF8);
string sLine;
sLine = objReader.ReadToEnd();
Console.WriteLine(sLine);发布于 2013-11-06 22:29:02
是压缩的内容。处理这一问题的最简单方法是添加
wrGetURL.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;在你得到回应之前。
希望这能帮上忙
https://stackoverflow.com/questions/19823867
复制相似问题