如何获得与WinPhone WebClient返回的HTTP状态码

本文关键字:HTTP 状态 返回 WebClient 何获得 WinPhone | 更新日期: 2023-09-27 18:06:59

我需要发送一段文本到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状态码则不设置。

如何获得与WinPhone WebClient返回的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);
        }