我正在使用WebClient
类将一些数据发布到web表单。我想要获取表单提交的响应状态代码。到目前为止,我已经了解了如何在出现异常时获取状态代码
Catch wex As WebException
If TypeOf wex.Response Is HttpWebResponse Then
msgbox(DirectCast(wex.Response, HttpWebResponse).StatusCode)
End If
但是,如果表单提交成功并且没有抛出异常,那么我将不知道状态代码(200,301,302,...)
有没有办法在没有抛出异常的情况下获得状态码?
PS:我不喜欢使用httpwebrequest/httpwebresponse
发布于 2010-08-26 19:43:11
试过了。ResponseHeaders不包括状态代码。
如果我没记错的话,WebClient
能够在单个方法调用中抽象出多个不同的请求(例如,正确处理100个Continue响应、重定向等)。我怀疑如果不使用HttpWebRequest
和HttpWebResponse
,可能无法获得不同的状态代码。
我想,如果您对中间状态码不感兴趣,那么您可以放心地假定最终状态码在2xx (成功)范围内,否则调用不会成功。
遗憾的是,ResponseHeaders
字典中不存在状态代码。
发布于 2012-02-09 23:37:26
您可以检查错误是否为WebException
类型,然后检查响应代码;
if (e.Error.GetType().Name == "WebException")
{
WebException we = (WebException)e.Error;
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
if (response.StatusCode==HttpStatusCode.NotFound)
System.Diagnostics.Debug.WriteLine("Not found!");
}
或
try
{
// send request
}
catch (WebException e)
{
// check e.Status as above etc..
}
发布于 2011-06-24 23:56:08
有一种方法可以使用反射来做到这一点。它适用于.NET 4.0。它访问私有字段,在没有修改的情况下可能无法在其他版本的.NET中工作。
我不知道为什么微软不用一个属性公开这个字段。
private static int GetStatusCode(WebClient client, out string statusDescription)
{
FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic);
if (responseField != null)
{
HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse;
if (response != null)
{
statusDescription = response.StatusDescription;
return (int)response.StatusCode;
}
}
statusDescription = null;
return 0;
}
https://stackoverflow.com/questions/3574659
复制相似问题