首页 > 代码库 > HttpWebRequest 返回BadRequest(400) 同时返回Response

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 =http://www.mamicode.com/ 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