我需要将一段文本发送到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 { }
当服务器返回400-500错误代码时,将设置当前e.Error
,但如果服务器返回300系列HTTP状态代码,则不会设置{{1}}。
答案 0 :(得分: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);
}