如何从HttpRequestException获取JSON错误消息
本文关键字:JSON 错误 消息 获取 HttpRequestException | 更新日期: 2023-09-27 17:51:01
我有一种情况,我必须在catch
语句中提取响应(HttpResponseMessage
),但我认为不能这样做(在catch中使用await
)。此外,如果我在捕获后这样做,HttpResponseMessage
消息得到"处置"。代码:
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);
}
}
我强烈怀疑问题是异常是实际上是抛出的调用EnsureSuccessStatusCode
,其文档包含:
如果Content不为空,此方法还将调用Dispose来释放托管和非托管资源。
基本上听起来,如果你需要失败时的内容,就不应该使用这个方法来确定成功或失败。
只需自己检查状态代码,并根据该代码适当地使用内容。注意,在catch块中,如果请求完全失败,response
很容易为null。
正确的方法是在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块用于处理异常条件。如果需要重新抛出,但应该避免。
Response应该只在远程服务器实际响应的情况下可用。如果响应是null
(我理解这是你的情况),这意味着由于某些原因,请求没有交付或响应没有收到(不衡量哪个响应-代码200 (OK)或任何其他代码(错误))。请检查错误代码(we.Status
)。确保它等于WebExceptionStatus.ProtocolError
(即,服务器响应错误);