HttpWebRequest 返回BadRequest(400)

问题背景:

使用 HttpWebRequest 调用 GetResponse() 方法,返回 WebException,HttpStatusCode 是 400,无法获取返回的错误信息;

解决方式:

在 catch 中捕获 WebException 异常,处理返回的详细信息

try
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    var response = (HttpWebResponse)request.GetResponse();
    ...
}
catch (WebException ex)
{
    var strError = ex.Message;
    using (WebResponse res = ex.Response)
    {
        var httpResponse = (HttpWebResponse)res;
        using (Stream data = res.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(data))
            {
                strError = reader.ReadToEnd();
            }
        }
        statusCode = httpResponse.StatusCode;
    }
    if (ex.Status != WebExceptionStatus.ProtocolError)
        throw;
    
    responseBody = strError;
}

 

posted on 2022-03-24 15:07  积跬步---行千里  阅读(494)  评论(0编辑  收藏  举报