异步请求数据(C#)

C# 实现异步请求下载数据:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

using System.Threading.Tasks;
using System.Configuration;

namespace Quartz.Net.Demo
{
    // This class stores the State of the request.
    public class RequestState
    {
        public int BufferSize = 1024;
        public string savepath = System.AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["filepath"].ToString();
        public byte[] BufferRead;
        public HttpWebRequest request;
        public HttpWebResponse response;
        public Stream streamResponse;

        public FileStream filestream;
        public RequestState()
        {
            BufferRead = new byte[BufferSize];
            request = null;
            streamResponse = null;
            if (File.Exists(savepath))
            {
                File.Delete(savepath);
            }
           
            filestream = new FileStream(savepath, FileMode.OpenOrCreate);
        }
    }
   public static class AsyncRequest
    {
        #region use APM to download file asynchronously

       /// <summary>
       /// 异步请求下载URL
       /// </summary>
       /// <param name="url">请求地址</param>
       /// <param name="method">post/get</param>
        /// <param name="objencoding">参数编码格式(utf-8,hz-gb-2312...)</param>
       /// <param name="objCookieContainer"></param>
       /// <param name="rescookie"></param>
        /// <param name="strContentType">请求内容类型</param>
       /// <param name="postDatas">post的参数数组</param>
       public static void DownloadFileAsync(string url, string method,string objencoding, ref CookieContainer objCookieContainer, ref string rescookie, string strContentType = "application/x-www-form-urlencoded", params string[] postDatas)
        {
            try
            {
                // Initialize an HttpWebRequest object
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

                // Create an instance of the RequestState and assign HttpWebRequest instance to its request field.
                RequestState requestState = new RequestState();
                requestState.request = myHttpWebRequest;
                requestState.request.Method = method;
                requestState.request.KeepAlive = true;
                requestState.request.Headers.Add("Cache-Control", "no-cache");
                requestState.request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                requestState.request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0";
                requestState.request.ContentType = strContentType;
                if (objCookieContainer == null)
                    objCookieContainer = new CookieContainer();
                //设置HttpWebRequest的CookieContainer,为刚才建立的那个objCookieContainer
                requestState.request.CookieContainer = objCookieContainer;

                string data = string.Empty;
                if (postDatas != null && postDatas.Length != 0)
                {
                    data = string.Join("&", postDatas);
                }
                byte[] bytes = Encoding.GetEncoding(objencoding.Trim()).GetBytes(data);
                if (method.ToUpper()=="POST")
                {
                    //Stream requestStream = requestState.request.GetRequestStream();
                    //requestStream.Write(bytes, 0, bytes.Length);
                    //requestStream.Close();
                }


                myHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), requestState);
                 
                //objCookieContainer = requestState.request.CookieContainer;
                //CookieCollection mycookie = objCookieContainer.GetCookies(requestState.request.RequestUri);
                //foreach (Cookie cook in mycookie)
                //{
                //    rescookie += cook.Name + "=" + cook.Value;
                //}  
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Message is:{0}", e.Message);
            }
        }

        // The following method is called when each asynchronous operation completes. 
        private static void ResponseCallback(IAsyncResult callbackresult)
        {
            // Get RequestState object
            RequestState myRequestState = (RequestState)callbackresult.AsyncState;

            HttpWebRequest myHttpRequest = myRequestState.request;

            // End an Asynchronous request to the Internet resource
            myRequestState.response = (HttpWebResponse)myHttpRequest.EndGetResponse(callbackresult);

            //1.这里可以获取cookie
            CookieCollection mycookie= myHttpRequest.CookieContainer.GetCookies(myHttpRequest.RequestUri);
            // 2.          
            //CookieCollection cookies=myRequestState.response.Cookies;

            //TODO:操作cookie


            // Get Response Stream from Server
            Stream responseStream = myRequestState.response.GetResponseStream();
            myRequestState.streamResponse = responseStream;

            IAsyncResult asynchronousRead = responseStream.BeginRead(myRequestState.BufferRead, 0, myRequestState.BufferRead.Length, ReadCallBack, myRequestState);
        }

        // Write bytes to FileStream
        private static void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {
                // Get RequestState object
                RequestState myRequestState = (RequestState)asyncResult.AsyncState;

                // Get Response Stream from Server
                Stream responserStream = myRequestState.streamResponse;

                // 
                int readSize = responserStream.EndRead(asyncResult);
                if (readSize > 0)
                {
                    myRequestState.filestream.Write(myRequestState.BufferRead, 0, readSize);
                    responserStream.BeginRead(myRequestState.BufferRead, 0, myRequestState.BufferRead.Length, ReadCallBack, myRequestState);
                }
                else
                {
                    Console.WriteLine("\nThe Length of the File is: {0}", myRequestState.filestream.Length);
                    Console.WriteLine("DownLoad Completely, Download path is: {0}", myRequestState.savepath);
                    myRequestState.response.Close();
                    myRequestState.filestream.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Message is:{0}", e.Message);
            }
        }
        #endregion
      
    }
}
AsyncRequest

 

调用上面的异步方法

 System.Net.CookieContainer objCookieContainer = null;
string rescookie=string.Empty;
//异步下载WebService中数据
AsyncRequest.DownloadFileAsync("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName"
                     , "POST", "utf-8", ref objCookieContainer, ref rescookie, "application/x-www-form-urlencoded", new string[1] { "theCityName=深圳" });
               

 

C# HttpWebRequest 绝技http://www.sufeinet.com/thread-6-1-1.html  

posted on 2015-03-19 11:52  二狗你变了  阅读(799)  评论(0)    收藏  举报

导航