如何从HttpRequestException获取JSON错误消息

时间:2013-01-08 04:24:40

标签: c# dotnet-httpclient

我有一种情况,我必须在HttpResponseMessage语句中提取响应(catch),但我认为无法完成(在catch中使用await)。 此外,如果我在catch之后执行此操作,HttpResponseMessage消息将获得“Disposed”。 代码:

 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);
    }
}

3 个答案:

答案 0 :(得分:9)

我强烈怀疑问题是,您EnsureSuccessStatusCode的{​​{1}}调用response调用了实际异常

  

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

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

请自行检查状态代码,并根据该代码正确使用内容。请注意,如果请求完全失败,在catch块{{1}}中很容易为空。

答案 1 :(得分:2)

执行此操作的正确方法是在try块本身

try
{
    response = await httpClient.PostAsync(url, httpContent);

    netResults = await response.Content.ReadAsStringAsync();
     //do something with the result
}
catch(HttpRequestException ex)
{
     // catch any exception here
}

Catch块用于处理异常情况。如果需要,可以使用Rethrow,但应该避免使用。

答案 2 :(得分:0)

仅当远程服务器实际响应时才应提供响应。如果响应是null(据我所知这是你的情况),这意味着由于某些原因,请求未被传递或未收到响应(没有得到响应 - 使用代码200(好的) )或任何其他代码(错误))。请检查错误代码(we.Status)。确保它等于WebExceptionStatus.ProtocolError(即服务器响应错误);否则,发生了一些其他错误,并且响应不应该可用。