1

我需要向 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 状态代码则不设置。

4

1 回答 1

1

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

 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);
        }
于 2013-04-02T16:39:30.663 回答