gpt4 book ai didi

c# - 如何从 HttpRequestException 获取 JSON 错误消息

转载 作者:行者123 更新时间:2023-11-30 19:10:56 25 4
gpt4 key购买 nike

我有一种情况,我必须在 catch 语句中提取 Response(HttpResponseMessage) 但我认为无法完成(使用 等待 在捕获中)。此外,如果我在 catch 之后执行此操作,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 的调用抛出了异常实际上,其 documentation包含:

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

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

只需自己检查状态代码,并根据该代码适本地使用内容。请注意,在您的 catch block 中,如果请求完全失败,response 很容易为 null。

关于c# - 如何从 HttpRequestException 获取 JSON 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com