HttpWebRequest请求返回非200的时候 HttpWebResponse怎么接受返回错误提示
2016-01-26 15:40
926 查看
当我们使用HttpWebRequest发送请求的时候如果服务器返回的不是200状态,那么请求代码肯定会异常,其实请求和返回并没有什么异常,只是.net内部就认定了 返回的不要是200 就是异常
那么我们怎么捕获这个HttpWebResponse异常呢
那么我们怎么捕获这个HttpWebResponse异常呢
try { HttpWebRequest httpReq = WebRequest.Create(Url) as HttpWebRequest; WebResponse wenReq = null; HttpWebResponse httpRes = null; string OutHtml = ""; try { httpReq.Method = "POST"; //................. //写入参数 byte[] postData = Encoding.UTF8.GetBytes(parmst);//参数编码UTF-8 System.IO.Stream outputStream = httpReq.GetRequestStream(); outputStream.Write(postData, 0, postData.Length); outputStream.Close(); //这里如果服务器不返回200状态就会报异常 wenReq = httpReq.GetResponse(); httpRes = wenReq as HttpWebResponse; Stream strRes = httpRes.GetResponseStream(); using (StreamReader read = new StreamReader(strRes, Encoding.UTF8)) { OutHtml = read.ReadToEnd(); } httpReq.Abort(); strRes.Close(); strRes.Dispose(); httpRes.Close(); } catch (WebException ex) // 这样我们就能捕获到异常,并且获取服务器端的输出 { wenReq = (HttpWebResponse)ex.Response; using (StreamReader sr = new StreamReader(wenReq.GetResponseStream(), Encoding.UTF8)) { LogResult(Url + ";Exception Err:" + ex.Message + ";Err JSON:" + sr.ReadToEnd(), "httperr"); } httpReq.Abort(); } catch (Exception ex) { //bgTask g = new bgTask(); LogResult(Url + ";Exception Err:" + ex.Message, "httperr"); }
相关文章推荐
- AngualrJS中每次$http请求时的一个遮罩层Directive
- 深入Android通过Apache HTTP访问HTTP资源
- Exception in thread "http-bio-8081-exec-3" java.lang.OutOfMemoryError: PermGen space
- HAProxy一箭双雕——让一个端口完成两件事
- Android网络请求的第三库AsyncHttpclient
- 理解HTTP幂等性
- AngualrJS中每次$http请求时的一个遮罩层Directive
- linux网络子系统内核分析
- android Xutils Http模块分析
- JAVA利用HttpClient进行POST请求(HTTPS)
- DHT网络存储设计
- 项目修炼之路(2)测试-TCPCopy
- java网络编程(一)使用TCP协议完成客户端与服务端的数据传递
- http头文件User-Agent详解
- http header详解
- SGU 176 Flow construction-上下界网络流
- VirtualBox配置网络以及SSH登陆配置
- 网络资源:常用的图表类库插件
- Ubuntu NetworkManager 使用:Ubuntu的wired Networks 变灰色,无法连接网络
- CentOS minimal安装后网络配置