The HttpWebRequest asynchronous Http send the BeginGetResponse

About http sent asynchronously, the beginning of my practice is with thread or task to accomplish; HttpWebRequest later found itself provides an asynchronous method.

Always feel .Net asynchronous method to provide their own might be better than a good use of our own thread to achieve;

Of course this is just my guess. If a large number of personal feeling good or asynchronous send asynchronous method HttpWebRequest itself provides.

Own package of the asynchronous request under HttpWebRequest.

/// <Summary>
        /// asynchronous HTTP request
        /// </ Summary>
        /// <param name = "URL"> URL </ param>
        /// <param name = "reqMethod"> request method GET, the POST </ param>
        /// <param name = "the callback"> callback </ param>
        /// <param name = "OB"> Object backhaul </ param>
        /// <param name = "postData" > post data </ param>
        public static void HttpAsyncRequest (URL String, String reqMethod, AsyRequetCallback the callback, Object OB = null, postData String = "")
        {
            Stream requestStream = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/x-www-form-urlencoded";
                = reqMethod request.method;
                IF (reqMethod.ToUpper () == "the POST")
                {
                    byte [] bytes = Encoding.UTF8.GetBytes (postData);
                    request.ContentLength = bytes.Length;
                    requestStream request.GetRequestStream = ();
                    requestStream.Write (bytes, 0, bytes.Length);
                }
                // start the asynchronous invocation request
                // AsyResultTag custom class for communicating information which must be passed HttpWebRequest object is invoked.
                // Because HttpWebRequest callback needed to obtain the HttpWebResponse
                request.BeginGetResponse (the AsyncCallback new new (HttpCallback), new new AsyResultTag () {obj = OB, the callback = the callback, REQ = Request});
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }
        }


        /// <the Summary>
        /// http request a callback call parameters must be internally .net IAsyncResult
        /// </ the Summary>
        /// <param name = "asynchronousResult"> http callback objects return </ param>
        Private void HttpCallback static (the IAsyncResult asynchronousResult)
        {
            int statusCode = 0;
            String retString = "";
            AsyResultTag new new AsyResultTag Tag = ();
            the WebException WebEx = null;
            the try
            {
                transmitted when acquiring the requested object //
                tag = asynchronousResult.AsyncState as AsyResultTag;
                REQ = tag.req the HttpWebRequest;
                // get the results of asynchronous http returned
                HttpWebResponse response = req.EndGetResponse(asynchronousResult) as HttpWebResponse;
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                statusCode = ((int)response.StatusCode);

            }
            The catch (the WebException EX)
            {
                IF ((the HttpWebResponse) ex.Response = null!)
                {
                    StatusCode = ((int) ((the HttpWebResponse) ex.Response) .StatusCode);
                }
               
                WebEx = EX;
            }
            // i.e. calling external callback outermost callback
            tag.callback (tag.obj, retString, statusCode, webEx);

        }

      /// <the Summary>
      /// asynchronous callback delegate request
      /// </ the Summary>
      /// <param name = "asyObj"> Return Object </ param>
      /// <param name = "ResStr"> HTTP response result </ param>
      /// <param name = "statusCode"> HTTP status code </ param>
      /// <param name = "WebEx"> abnormalities </ param>
      public void AsyRequetCallback the delegate (Object asyObj, String respStr , int statusCode, WebException webEx);

    /// <Summary>
    /// Returns an object asynchronous
    /// </ Summary>
    class AsyResultTag
    {
        /// <Summary>
        /// Return an object
        /// </ Summary>
        public Object obj {GET; SET;}
        /// <Summary>
        /// this instance request httpRequest
        /// </ Summary>
        public the HttpWebRequest REQ {GET; SET;}
        /// <Summary>
        /// callback delegate
        /// </ Summary>
        public AsyRequetCallback {GET the callback; SET;}
    }

AsyRequetCallback asynchronous callback delegate that function prototypes for callbacks; sense under each parameter:

1, object asyObj: return the object, an object that is included with the request, if not you can not pass. For example, we present this request and has been associated users, such as the current corresponding to this request is a user after a request I want to write the results to the user of a property below; so that we can use this information and current user request carries the past.
2, string respStr: http return the current result.

3, int statusCode: http status codes, including error status code. Such as 404,403 and so on.

4, WebException webEx abnormality information, abnormality information is also passed as a callback to the front, does not directly up or directly cast log. Benefit is that we can do alone for this exception processing information. For example, a user 403 or 404 if you encounter what we should be how to deal with, or we may be wrong with the current user to save information, send a good track each user's situation.

Guess you like

Origin www.linuxidc.com/Linux/2019-12/161825.htm