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

今天用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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。