当C#创建HTTP GET请求时,Stackoverflow API返回意外响应.
如果我将http://api.stackoverflow.com/1.1/users/882993粘贴到浏览器地址栏中,我会得到正确的JSON响应:
{ "total": 1,"page": 1,"pagesize": 30,"users": [ { "user_id": 882993,"user_type": "registered","creation_date": 1312739131,"display_name": "Jack","reputation": 1926,"email_hash": "69243d90e50d9e0b3e025517fd23d1da","age": 23,"last_access_date": 1358087009,"website_url": "http://jtbrown.me.uk","location": "Birmingham,United Kingdom","about_me": "<p>Student.</p>\n","question_count": 68,"answer_count": 79,"view_count": 115,"up_vote_count": 98,"down_vote_count": 3,"accept_rate": 94,"association_id": "d64187a3-bf66-4a4d-8e87-6ef18f0397e3","user_questions_url": "/users/882993/questions","user_answers_url": "/users/882993/answers","user_favorites_url": "/users/882993/favorites","user_tags_url": "/users/882993/tags","user_badges_url": "/users/882993/badges","user_timeline_url": "/users/882993/timeline","user_mentioned_url": "/users/882993/mentioned","user_comments_url": "/users/882993/comments","user_reputation_url": "/users/882993/reputation","badge_counts": { "gold": 0,"silver": 7,"bronze": 34 } } ] }
如果我尝试在代码中执行相同的操作:
HttpWebRequest Request = WebRequest.Create("http://api.stackoverflow.com/1.1/users/882993") as HttpWebRequest; using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader Reader = new StreamReader(Response.GetResponseStream()); // Console application output StackWidget.Text = Reader.ReadToEnd(); }
我收到了回复:
�\b\0\0\0\0\0\0u�Ms�0���`8��Ӏ2�rl����#���J4��^\t#�p�g���j�����|�n�G/ڎ�7p����$�5\r���f�y�v�����\"F(���֛0���J�?{��������$���e�!T�-~+��@_p���j\fb�(�f�my��dt�ӄ�!AV\t����G'$\"؉i{;��X��5H9�z(�\"GQ<�]��TA9\b�Z��T��U%���;�n�-����*:ʚ��w�c��yU|P�m�S��M\r��?��O���@�m������\n'\b�}/�ь�.7E\a�*���uaDN@�k��N�L�zU\n�3�:DJ^S{����$K�\"�ɮ:f�.�)�P�\f�Qq\f�C�/�k*UN=�A\r�,7���.���p�9�3�jVT7��)ܬH\fYzW�4kGX�_|�AK��q�KU�GGw��^�j����D���7�\\��Ƴr,�N�yzno�F\ro�̄[�&i{afڵ��ٗ,���c\\~=l>6�\0U�F\0\0
解决方法
您收到的HTTP响应是GZIP压缩的,因此您必须解压缩响应流.这可以通过设置
HttpWebRequest.AutomaticDecompression
属性自动完成.
var request = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/users/882993"); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); }