导航

HttpWebRequest 出错后抓详细的错误原因

Posted on 2012-12-13 16:36  杨彬Allen  阅读(377)  评论(0)    收藏  举报
        public byte[] Dowload()
        {
            try
            {
                if (_method == "GET")
                {
                    _httpUrl += "?" + _data;
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(_httpUrl);
                httpWebRequest.Method = _method;

                if (_method == "POST")
                {
                    httpWebRequest.ContentLength = _data.Length;
                    Stream requestStream = httpWebRequest.GetRequestStream();
                    requestStream.Write(_data, 0, _data.Length);
                    requestStream.Close();
                }

                var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream stream = httpWebResponse.GetResponseStream();
                var bytes = new List<byte>();
                int value = stream.ReadByte();
                while (value != -1)
                {
                    bytes.Add(Convert.ToByte(value));
                    value = stream.ReadByte();
                }

                return bytes.ToArray();
            }

            catch (WebException we)
            {
                using (StreamReader sr =  new StreamReader(we.Response.GetResponseStream()))
                {
                    //此处可以取得错误的详细原因
                    string error = sr.ReadToEnd();
                    return new byte[] { };
                }
            }
            catch (Exception ex)
            {
                //此处取不到错误的详细原因
                //一般只会报类似500错误。
                string error = ex.Message;
                return new byte[] { };
            }
        }

如果只是简单的写catch (Exception ex)是抓不到详细信息的,在这里可以用catch (WebException we)来抓详细的错误信息。