HttpWebRequest请求返回非200的时候 HttpWebResponse怎么接受返回错误提示
当我们使用HttpWebRequest发送请求的时候如果服务器返回的不是200状态,那么请求代码肯定会异常,其实请求和返回并没有什么异常,只是.net内部就认定了 返回的不要是200 就是异常
那么我们怎么捕获这个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"); }