How to get status code from webclient?

前端 未结 10 1750
轮回少年
轮回少年 2020-11-29 04:03

I am using the WebClient class to post some data to a web form. I would like to get the response status code of the form submission. So far I\'ve found out how

相关标签:
10条回答
  • 2020-11-29 04:40

    Just in case someone else needs an F# version of the above described hack.

    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()
    
    0 讨论(0)
  • 2020-11-29 04:44

    Tried it out. ResponseHeaders do not include status code.

    If I'm not mistaken, WebClient is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available.

    It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

    The status code unfortunately isn't present in the ResponseHeaders dictionary.

    0 讨论(0)
  • 2020-11-29 04:45

    You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

    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;
    }
    
    0 讨论(0)
  • 2020-11-29 04:46

    You should be able to use the "client.ResponseHeaders[..]" call, see this link for examples of getting stuff back from the response

    0 讨论(0)
  • 2020-11-29 04:48

    There is a way to do it using reflection. It works with .NET 4.0. It accesses a private field and may not work in other versions of .NET without modifications.

    I have no idea why Microsoft did not expose this field with a property.

    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;
    }
    
    0 讨论(0)
  • 2020-11-29 04:49

    If you are using .Net 4.0 (or less):

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

    If you are using .Net 4.5.X or newer, switch to HttpClient:

    var response = await client.GetAsync("http://www.contoso.com/");
    var statusCode = response.StatusCode;
    
    0 讨论(0)
提交回复
热议问题