c# HttpWebRequest 返回BadRequest(400)的信息读取

c# HttpWebRequest 返回BadRequest(400)的信息读取

问题:

使用 HttpWebRequest 调用 GetResponse() 方法,返回 WebException,HttpStatusCode 是 400,无法获取返回的错误信息;

解决方法:

在 catch 中捕获 WebException 异常,处理返回的详细信息

 public static HttpWebResponse CreateTaskOrder(string url, string json, ref string return_message)
        {
            Console.WriteLine(url);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
            request.Method = "POST";//请求方式
            request.ContentType = "application/json";//链接类型
            HttpWebResponse webResponse= null;
           // webResponse = request.GetResponse() as HttpWebResponse;
            try
            {
                if (!(json == null))
                {
                    Console.WriteLine(json);
                    byte[] data = Encoding.UTF8.GetBytes(json);
 
                    //写入请求流
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
 
                Thread.Sleep(500);
 
                webResponse = request.GetResponse() as HttpWebResponse;
 
 
                using (Stream s = webResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(s, Encoding.UTF8);
                    return_message = reader.ReadToEnd();
                }
 
 
 
                //  erro = "订单请已发送....";
                return request.GetResponse() as HttpWebResponse;
            }
            catch (System.Net.WebException ex) //by txwtech
            {
                var strError = ex.Message;
                using (WebResponse res = ex.Response)
                {
                    var httpResponse = (HttpWebResponse)res;
                    using (Stream data = res.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(data))
                        {
                            strError = reader.ReadToEnd();
                        }
                    }
                  //  statusCode = httpResponse.StatusCode;
                }
                if (ex.Status != WebExceptionStatus.ProtocolError)
                    throw;
 
                // responseBody = strError;
 
                //erro = ex.ToString();
                // erro = "error";
                // return_message = "网络异常\r\n请求超时\r\n" + ex.StackTrace;
                return_message = strError;
                return null;
            }                                       //构造查询字符串
 
        }

 

posted @ 2022-08-12 15:36  txwtech  阅读(693)  评论(0编辑  收藏  举报