使用 C#
的 HttpWebRequest
请求接口如果接口返回了 401
则会抛出异常,而 401
其实也有可能返回正常的响应数据,如何获取异常时的响应流?
解决方案
捕获 WebException
异常,通过 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等错误返回的有效信息}Stream stream = resp.GetResponseStream();using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)){result = reader.ReadToEnd();}return result;
}