使用 HttpWebRequest 获取错误数据

Get data on error with HttpWebRequest

在与 API 互动时,他们会 return 一个也包含数据的 401 响应。无论响应的错误代码如何,我都想 return 此数据。

我创建了一个函数来提交 GET 或 POST 使用 HttpWebRequest returns 一个包含响应数据的字符串。唯一的问题是,如果响应是 401,则会抛出错误并且不会读取数据。

这是 returned 的示例:

HTTP/1.1 401 Unauthorized
Access-Control-Allow-Credentials: false
Content-Type: application/json; charset=UTF-8
Date: Tue, 19 May 2015 17:56:10 GMT
Vary: Accept-Encoding
Vary: Accept-Encoding
Content-Length: 254
Connection: keep-alive

{"status":"error","message":"access_token (...) was deleted (at Tue May 19 17:52:49 UTC 2015).  Use your refresh token (if you have one) to generate a new access_token.","requestId":"..."}

到目前为止,这是我的函数:

private string SendHttpRequest(string url, out int statusCode, string method = "GET", object postData = null, string contentType = "application/json")
{
    bool isPost = method.Equals("POST", StringComparison.CurrentCultureIgnoreCase);

    byte[] content = new ASCIIEncoding().GetBytes(isPost ? JsonConvert.SerializeObject(postData) : "");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.AllowAutoRedirect = true;
    request.Method = method;
    request.ContentType = contentType;
    request.ContentLength = postData == null ? 0 : content.Length;

    if (isPost && postData != null)
    {
        Stream reqStream = request.GetRequestStream();
        reqStream.Write(content, 0, content.Length);
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Throws error here

    string result;

    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        result = sr.ReadToEnd();
    }
    statusCode = (int)response.StatusCode;

    response.Close();

    return result;
}

我怎样才能仍然获得 401 响应的数据?没有要求使用 HttpWebRequest,这正是我到目前为止一直在使用的。

GetResponse 的调用抛出 WebException。您可以捕获该异常并通过异常的 Response 属性:

提取响应
private string SendHttpRequest(string url, out int statusCode, string method = "GET", object postData = null, string contentType = "application/json")
{
    bool isPost = method.Equals("POST", StringComparison.CurrentCultureIgnoreCase);

    byte[] content = new ASCIIEncoding().GetBytes(isPost ? JsonConvert.SerializeObject(postData) : "");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.AllowAutoRedirect = true;
    request.Method = method;
    request.ContentType = contentType;
    request.ContentLength = postData == null ? 0 : content.Length;

    if (isPost && postData != null)
    {
        Stream reqStream = request.GetRequestStream();
        reqStream.Write(content, 0, content.Length);
    }

    HttpWebResponse response = null;

    //Get the response via request.GetResponse, but if that fails,
    //retrieve the response from the exception
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
        response = (HttpWebResponse)ex.Response;
    }

    string result;

    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        result = sr.ReadToEnd();
    }
    statusCode = (int)response.StatusCode;

    response.Close();

    return result;
}