gpt4 book ai didi

c# - Windows Phone - 如何获取 HTTP 状态代码?

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:05 26 4
gpt4 key购买 nike

我不得不手动连接我的网络层。要针对 Web 服务运行查询,我使用以下代码:

public void RunService()
{
string serviceUrl = Constants.URL_OF_SERVICE;
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(Service_Completed), request);
}

private void Service_Completed(IAsyncResult result)
{
try
{
WebRequest request = (WebRequest)(result.AsyncState);
WebResponse response = request.EndGetResponse(result);

// Continue doing stuff
}
catch (WebException ex1)
{
// How do I get the HTTP Status code here?
}
}

发生错误时,我无法获取 HTTP 状态代码。有人可以告诉我如何在抛出 WebException 时获取 HTTP 状态代码吗?

谢谢!

最佳答案

使用 WebResponse part of the WebException :

catch (WebException ex1)
{
using (HttpWebResponse response = (HttpWebResponse) ex1.Response)
{
if (response == null)
{
// Whatever
}
else
{
HttpStatusCode status = response.StatusCode;
// Whatever
}
}
}

关于c# - Windows Phone - 如何获取 HTTP 状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7687719/

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