C# WebException 获取http错误码和错误消息
C#发送http请求时,如果服务器返回了错误码和错误消息,按照传统模式就是直接抛出“系统异常”,然后把错误写入日志。这种方式不是很友好,于是调整代码,根据不同的错误码给出友好提示。核心代码如下:
static void Main(string[] args) { try { WebClient web = new WebClient(); var str = web.DownloadString("http://localhost:31005/Home/MyTest"); Console.WriteLine(str); } catch (WebException ex) { HttpWebResponse response = (HttpWebResponse)ex.Response; Console.WriteLine("错误码:" + (int)response.StatusCode); Console.WriteLine("错误码描述:" + response.StatusDescription); var stream = response.GetResponseStream(); stream.Position = 0; byte[] bs = new byte[stream.Length]; stream.Read(bs, 0, bs.Length); Console.WriteLine("错误消息:"+ Encoding.UTF8.GetString(bs)); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); }