zoukankan      html  css  js  c++  java
  • 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");
                    }
        
    

      

  • 相关阅读:
    C++中堆和栈的区别
    JavaScript 点击切换菜单
    正则表达式过滤掉CSS样式
    单例模式DEMO
    将来的你,一定会感谢现在努力的自己
    1066 图像过滤 (15 分)
    1076 Wifi密码 (15 分)
    1071 小赌怡情 (15 分)
    1046 划拳 (15 分)
    1086 就不告诉你 (15 分)
  • 原文地址:https://www.cnblogs.com/sxmny/p/5160601.html
Copyright © 2011-2022 走看看