【转】C# HttpWebRequest 异常时获取 HttpWebResponse 数据
生活随笔
收集整理的這篇文章主要介紹了
【转】C# HttpWebRequest 异常时获取 HttpWebResponse 数据
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用?C#?的?HttpWebRequest?請(qǐng)求接口如果接口返回了?401?則會(huì)拋出異常,而?401?其實(shí)也有可能返回正常的響應(yīng)數(shù)據(jù),如何獲取異常時(shí)的響應(yīng)流?
解決方案
捕獲?WebException?異常,通過(guò)?ex.Response?獲取?HttpWebResponse
主要代碼如下:
private string Request(string url, string method, byte[] body, string contentType) {HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);HttpWebResponse resp;try{resp = (HttpWebResponse)req.GetResponse();}catch (WebException ex){resp = (HttpWebResponse)ex.Response; //解析401等錯(cuò)誤返回的有效信息}Stream stream = resp.GetResponseStream();using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)){result = reader.ReadToEnd();}return result; }?
總結(jié)
以上是生活随笔為你收集整理的【转】C# HttpWebRequest 异常时获取 HttpWebResponse 数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 交通银行信用卡刷卡金
- 下一篇: 交通银行白金卡机场贵宾厅有哪些