【代码】C#发送POST请求,并对非200返回做处理

2020-09-02 13:22:31  阅读 765 次 评论 0 条

我在之前写过一个有关于C#post请求的,详情移步这里

由于非200直接进入catch代码块,导致不知道网页输出的是什么错误,这个文章就对非200部分做了处理

 public static string RequestContent(string URL, string method, string postData, Dictionary<string, string> heads)
        {
            byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(postData);
            string result = string.Empty;
            try
            {

                HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(URL);
                //HttpWReq.Headers.Add("Accept-Encoding", "gzip,deflate");//sdch 

                HttpWReq.Method = method;

                if (method.ToUpper() == "POST")
                {
                    HttpWReq.ContentType = "application/x-www-form-urlencoded";
                    HttpWReq.ContentLength = postBytes.Length;
                    //HttpWReq.Headers.Add("Authorization","Unauthorized");
                    
                    using (Stream reqStream = HttpWReq.GetRequestStream())
                    {
                        reqStream.Write(postBytes, 0, postBytes.Length);
                    }
                }



                HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();

                StreamReader reader = new StreamReader(HttpWResp.GetResponseStream(), Encoding.Default);

                result = reader.ReadToEnd();

                HttpWResp.Close();
            }
            catch (WebException e)
            {
                //string msg = e.Message;
                HttpWebResponse response = (HttpWebResponse)e.Response;


                using (Stream data = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(data, Encoding.Default))
                    {
                        result = reader.ReadToEnd();
                    }
                }

            }
            return result;




        }



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2098
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?