如何从HttpRequestException获取JSON错误消息 [英] How to get the JSON error message from HttpRequestException

查看:314
本文介绍了如何从HttpRequestException获取JSON错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我必须在 catch 语句中提取Response( HttpResponseMessage ),但是我想做不到(在捕获中使用 await )。
另外,如果我在catch之后执行此操作,则 HttpResponseMessage 消息将获得已处置。
代码:

I have a situation where in I have to extract a Response(HttpResponseMessage) in a catch statement but that I suppose can't be done (using await in catch). Also if i do it after catch , the HttpResponseMessage message gets "Disposed". Code:

 private async void MakeHttpClientPostRequest()
 {
     HttpResponseMessage response = null;
     try
     {
         HttpClient httpClient = new HttpClient();
         httpClient.Timeout = TimeSpan.FromSeconds(15);
         HttpContent httpContent = null;
         if (postJSON != null)
         {
             httpContent = new StringContent(postJSON);
             httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
         }

         response = await httpClient.PostAsync(url, httpContent);
         if (response != null)
         {
             response.EnsureSuccessStatusCode();
             netResults = await response.Content.ReadAsStringAsync();
         }

         if (this.convertedType != null)
         {
             MemoryStream assetReader = GetMemoryStreamFromString(netResults);
             assetReader.Position = 0;
             object value = fromJSON(assetReader, this.convertedType);
             networkReqSuccessWithObjectCallback(this, value);
         }
         else
         {
             //Return netResult as string.
             networkReqSuccessWithStringCallback(this, netResults);
         }
     }

     catch (TaskCanceledException)
     {
         ErrorException ee = null;
         ee = new ErrorException("RequestTimeOut");
         NotifyNetworkDelegates(ee);
     }
     catch (HttpRequestException ex)
     {
         //HERE I have to extract the JSON string send by the server
     }
     catch (Exception)
     {
     }
}

在这里可以做什么?

更新
以前的方法使用 HttpWebRequest

public void MakePostWebRequest()
{
    //WebCalls using HttpWebrequest.
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.CookieContainer = new CookieContainer();
    request.ContentType = "application/json";
    request.Method = "POST";
    requestState = RequestState.ERequestStarted;
    asyncResult = request.BeginGetRequestStream(new AsyncCallback(GetRequestStream), request);
}


private void GetRequestStream(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    {
        try
        {
            Stream requestStream = request.EndGetRequestStream(asyncResult);
            if (request != null)
            {
                using (requestStream)
                {
                    StreamWriter writer = new StreamWriter(requestStream);
                    writer.Write(postJSON);
                    writer.Flush();
                }
            }
        }
        catch (WebException we)
        {
        }
    }
}

private void GetResponseStream(IAsyncResult asyncResult)
{
    requestState = RequestState.EResponseStream;

    HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.EndGetResponse(asyncResult);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            netResults = reader.ReadToEnd();
        }
        requestState = RequestState.ERequestCompleted;
    }
    catch (WebException we)
    {
        // failure
        ErrorException ee = null;
        response = we.Response as HttpWebResponse;
        if (response != null)
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                //HERE I'm getting the json error message
                netResults = reader.ReadToEnd();
            }
        }
    }
    catch (Exception e)
    {
        networkReqFailedCallback(this, e);
    }
}


推荐答案

I强烈怀疑问题在于您对 EnsureSuccessStatusCode 的调用实际上是 引发的,其文档包含:

I strongly suspect the problem is that the exception is actually thrown by your call to EnsureSuccessStatusCode, whose documentation contains:


如果Content不为null,则此方法还将调用Dispose以释放托管和非托管资源。

If the Content is not null, this method will also call Dispose to free managed and unmanaged resources.

基本上,听起来您应该如果您需要有关失败的内容,请不要使用该方法来确定成功或失败。

Basically it sounds like you shouldn't be using that method to determine the success or failure if you need the content on failure.

只需自己检查状态码,然后根据该内容适当地使用内容码。请注意,如果请求完全失败,则在catch块中的 response 很容易为空。

Just check the status code yourself, and use the content appropriately based on that code. Note that in your catch block response could very easily be null, if the request failed completely.

这篇关于如何从HttpRequestException获取JSON错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆