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

标签 c# http windows-phone-8 windows-phone webclient

我需要向 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/

相关文章:

wpf - 如何水平对齐按钮并使用 xaml windows phone 均匀分布

c# - 捕获二维码时屏幕挂起

c# - asp .net mvc 中带有 View 模型的多个路由参数

c# - .net c# 限制 observablecollection 中的条目数

c# - Elastic Search .NET Core 对 Post 的低级别调用不成功

angular - 类型错误 : Object doesn't support property or method 'map' - AngularJS2

node.js - 保护我的 HTTP 连接

http - 如何在 Firefox 中忽略 "Content-Disposition: attachment"

c# - 如何在 WSDL 中定义一组自定义类型?

c++ - 如何使用静态库(windows phone 8)