gpt4 book ai didi

c# - 如何获取 WinPhone WebClient 返回的 HTTP 状态码?

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:10:38 25 4
gpt4 key购买 nike

我需要向 HTTP 服务器发送一段文本。我需要相当确定地知道已成功发送,而不是发送到强制门户或类似门户。由于 HTTP 服务器的一些限制,我最好的确定方法是确保返回的 HTTP 状态代码为 200。

如何获取服务器返回的 HTTP 状态码?

这是我当前的代码:

        WebClient client = new WebClient();
client.Headers["Content-Type"] = "text/xml";
client.Encoding = Encoding.UTF8;
bool? result=null;
try
{
client.UploadStringAsync(server, "POST", data);
client.UploadStringCompleted += (s, e) =>
{
result=e.Error == null;
};
}
catch { }

目前 e.Error 将在服务器返回 400-500 错误代码时设置,但如果服务器返回 300 系列的 HTTP 状态代码则不会。

最佳答案

我没有机会测试这段代码,但是,它可能会给你一两个想法:

 string data;

var request = HttpWebRequest.Create("http://yourserver") as HttpWebRequest;
request.Accept = "text/xml";
request.Headers.Add("Accept-Charset", "utf-8");

try
{
var response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

// do something with your data, e.g. read it, deserialize it
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
// ....
}

var somethingInteresting = response as HttpWebResponse;
Debug.WriteLine("Status is {0}", somethingInteresting.StatusCode);
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
var errorHttpStatusCode = errorResponse.StatusCode;

Debug.WriteLine("Here's your error Http status: {0}", ex.Status);
}

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

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