Web Request请求失败的情况下,获取状态码和失败消息

一般http请求我们封装的HttpHepler用的比较多的都是 web request吧。

如果请求失败,能否同样获取状态码和失败消息呢? 使用WebException

            HttpWebRequest request = WebRequest.Create(RelUrl) as HttpWebRequest;
                request.Method = method;
                request.Headers.Add("aftership-api-key", ApiKey);
                if (!string.IsNullOrEmpty(requestData))
                {
                    request.ContentType = "application/json";
                    byte[] payload = Encoding.UTF8.GetBytes(requestData);
                    request.ContentLength = payload.Length;

                    //发送post的请求,写入参数
                    Stream writer = request.GetRequestStream();
                    writer.Write(payload, 0, payload.Length);
                    writer.Close();
                }
                try
                {
                    //如果请求失败,到这一步会报错。但是我们需要请求返回的状态码,就必须要“HttpWebResponse”对象
                    //可以把以下代码放到try里面,如果失败了,catch也能获取
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    Stream stream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    result = reader.ReadToEnd();

                    reader.Close();
                    stream.Close();
                    response.Close();
                }
                catch (WebException ex) //一定要是这个对象类型
                {
                    var response = (HttpWebResponse)ex.Response;
                    Stream myResponseStream = ex.Response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    return retString;
                }

 

posted on 2020-11-04 09:36  阿里正正  阅读(820)  评论(0编辑  收藏  举报

导航