简体   繁体   中英

How to get the HTTP Status Code returned with WinPhone WebClient?

I'm needing to send a piece of text to an HTTP server. I need to know with a decent amount of certainty that is was successfully sent, and not sent to a captive portal or some such. Because of some limitations with the HTTP server though, my best shot for determining that is to ensure that the returned HTTP status code is 200.

How can I get the HTTP status code returned from the server?

This is my current code:

        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 { }

Currently e.Error will be set when the server returns a 400-500 error code, but not if the server returns the 300 series of HTTP status codes.

I did not have a chance to test this code, however, it might give you an idea or two:

 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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM