我正在使用WebClient
类将一些数据发布到网络表单。我想获取表单提交的响应状态代码。到目前为止,我已经找到了如果有异常
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
答案 0 :(得分:80)
您可以检查错误是否为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..
}
答案 1 :(得分:28)
有一种方法可以使用反射来实现。它适用于.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;
}
答案 2 :(得分:27)
如果您使用的是.Net 4.0(或更低版本):
class BetterWebClient : WebClient
{
private WebRequest _Request = null;
protected override WebRequest GetWebRequest(Uri address)
{
this._Request = base.GetWebRequest(address);
if (this._Request is HttpWebRequest)
{
((HttpWebRequest)this._Request).AllowAutoRedirect = false;
}
return this._Request;
}
public HttpStatusCode StatusCode()
{
HttpStatusCode result;
if (this._Request == null)
{
throw (new InvalidOperationException("Unable to retrieve the status
code, maybe you haven't made a request yet."));
}
HttpWebResponse response = base.GetWebResponse(this._Request)
as HttpWebResponse;
if (response != null)
{
result = response.StatusCode;
}
else
{
throw (new InvalidOperationException("Unable to retrieve the status
code, maybe you haven't made a request yet."));
}
return result;
}
}
如果您使用的是.Net 4.5.X或更高版本,请切换到HttpClient:
var response = await client.GetAsync("http://www.contoso.com/");
var statusCode = response.StatusCode;
答案 3 :(得分:21)
试了一下。 ResponseHeaders不包含状态代码。
如果我没有弄错的话,WebClient
能够在单个方法调用中抽象出多个不同的请求(例如正确处理100个继续响应,重定向等)。我怀疑在不使用HttpWebRequest
和HttpWebResponse
的情况下,可能无法使用不同的状态代码。
在我看来,如果您对中间状态代码不感兴趣,您可以放心地假设最终状态代码在2xx(成功)范围内,否则,呼叫将不会成功。
遗憾的是,状态代码不存在于ResponseHeaders
字典中。
答案 4 :(得分:9)
Erik的答案在Windows Phone上不起作用。以下是:
class WebClientEx : WebClient
{
private WebResponse m_Resp = null;
protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
{
try
{
this.m_Resp = base.GetWebResponse(request);
}
catch (WebException ex)
{
if (this.m_Resp == null)
this.m_Resp = ex.Response;
}
return this.m_Resp;
}
public HttpStatusCode StatusCode
{
get
{
if (m_Resp != null && m_Resp is HttpWebResponse)
return (m_Resp as HttpWebResponse).StatusCode;
else
return HttpStatusCode.OK;
}
}
}
至少在使用OpenReadAsync
时会这样做;对于其他xxxAsync
方法,强烈建议进行仔细测试。框架在代码路径的某个地方调用GetWebResponse;所有需要做的就是捕获并缓存响应对象。
此代码段中的回退代码为200,因为正确的HTTP错误 - 500,404等 - 无论如何都会被报告为异常。这个技巧的目的是捕获非错误代码,在我的特定情况下304(未修改)。所以后备假设如果状态代码在某种程度上不可用,至少它是一个非错误的。
答案 5 :(得分:3)
你应该使用
if (e.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if (response.StatusCode == HttpStatusCode.NotFound)
System.Diagnostics.Debug.WriteLine("Not found!");
}
答案 6 :(得分:1)
以防其他人需要上述黑客的F#版本。
open System
open System.IO
open System.Net
type WebClientEx() =
inherit WebClient ()
[<DefaultValue>] val mutable m_Resp : WebResponse
override x.GetWebResponse (req: WebRequest ) =
x.m_Resp <- base.GetWebResponse(req)
(req :?> HttpWebRequest).AllowAutoRedirect <- false;
x.m_Resp
override x.GetWebResponse (req: WebRequest , ar: IAsyncResult ) =
x.m_Resp <- base.GetWebResponse(req, ar)
(req :?> HttpWebRequest).AllowAutoRedirect <- false;
x.m_Resp
member x.StatusCode with get() : HttpStatusCode =
if not (obj.ReferenceEquals (x.m_Resp, null)) && x.m_Resp.GetType() = typeof<HttpWebResponse> then
(x.m_Resp :?> HttpWebResponse).StatusCode
else
HttpStatusCode.OK
let wc = new WebClientEx()
let st = wc.OpenRead("http://www.stackoverflow.com")
let sr = new StreamReader(st)
let res = sr.ReadToEnd()
wc.StatusCode
sr.Close()
st.Close()
答案 7 :(得分:1)
这是我用于扩展WebClient功能的内容。 StatusCode和StatusDescription将始终包含最新的响应代码/说明。
/// <summary>
/// An expanded web client that allows certificate auth and
/// the retrieval of status' for successful requests
/// </summary>
public class WebClientCert : WebClient
{
private X509Certificate2 _cert;
public WebClientCert(X509Certificate2 cert) : base() { _cert = cert; }
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
if (_cert != null) { request.ClientCertificates.Add(_cert); }
return request;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = null;
response = base.GetWebResponse(request);
HttpWebResponse baseResponse = response as HttpWebResponse;
StatusCode = baseResponse.StatusCode;
StatusDescription = baseResponse.StatusDescription;
return response;
}
/// <summary>
/// The most recent response statusCode
/// </summary>
public HttpStatusCode StatusCode { get; set; }
/// <summary>
/// The most recent response statusDescription
/// </summary>
public string StatusDescription { get; set; }
}
因此,您可以通过以下方式发布帖子并获得结果:
byte[] response = null;
using (WebClientCert client = new WebClientCert())
{
response = client.UploadValues(postUri, PostFields);
HttpStatusCode code = client.StatusCode;
string description = client.StatusDescription;
//Use this information
}
答案 8 :(得分:-1)
您应该可以使用“client.ResponseHeaders [..]”调用,请参阅此link以获取从回复中获取内容的示例
答案 9 :(得分:-1)
您可以尝试使用此代码从WebException或OpenReadCompletedEventArgs.Error获取HTTP状态代码。它也适用于Silverlight,因为SL没有定义WebExceptionStatus.ProtocolError。
HttpStatusCode GetHttpStatusCode(System.Exception err)
{
if (err is WebException)
{
WebException we = (WebException)err;
if (we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
return response.StatusCode;
}
}
return 0;
}