今天用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 catch (Exception ex) 2 { 3 using (WebResponse response = e.Response) 4 { 5 HttpWebResponse httpResponse = (HttpWebResponse)response; 6 using (Stream data = response.GetResponseStream()){ 7 using (var reader = new StreamReader(data)) 8 { 9 string text = reader.ReadToEnd(); 10 Console.WriteLine(text); 11 } 12 } 13 } 14 }
这样就可以获取到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