码迷,mamicode.com
首页 > Web开发 > 详细

HttpWebRequest 返回BadRequest(400) 同时返回Response

时间:2014-08-23 01:00:39      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   问题   div   

今天用Fiddler分析安卓APP的一个登陆功能的时候,账号和密码错误会返回相应的消息,并且状态码是400。

 

正常用法:

 1         /// <summary>
 2         /// 读取返回的内容
 3         /// </summary>
 4         /// <param name="asyncresult"></param>
 5         private void ReadCallBack(IAsyncResult asyncresult)
 6         {
 7             String result = String.Empty;
 8             try
 9             {
10                 HttpWebRequest myrequest = (HttpWebRequest)asyncresult.AsyncState;
11                 HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asyncresult);
12 
13                 //读取返回对象
14                 Stream responseStream = response.GetResponseStream();
15 
16                 using (var render = new StreamReader(responseStream, Encoding.UTF8))
17                 {
18                     result = render.ReadToEnd();
19                     render.Close();
20                 }
21             }
22             catch (Exception ex)
23             {
24 
25                 Console.WriteLine("出现异常:" + ex.Message);
26             }
27             //处理返回消息
28             if (Handler != null)
29                 Handler(result);
30         }

当执行GetResponseStream就抛出异常了,异常提示是BadRequest.

要想获取400返回的信息,需要对catch部分做特殊处理。

添加catch代码:

 1                 using (WebResponse response = e.Response)
 2                 {
 3                     HttpWebResponse httpResponse = (HttpWebResponse)response;
 4                     using (Stream data = response.GetResponseStream())
 5                     using (var reader = new StreamReader(data))
 6                     {
 7                         string text = reader.ReadToEnd();
 8                         Console.WriteLine(text);
 9                     }
10                 }

这样就可以获取到400返回的消息了。

stackoverflow问题链接:

http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba

http://stackoverflow.com/questions/11660947/httpwebrequest-getresponse-throws-bad-request-400-error

HttpWebRequest 返回BadRequest(400) 同时返回Response

标签:style   blog   http   color   os   io   ar   问题   div   

原文地址:http://www.cnblogs.com/xcong/p/3930443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!