Windows Phone 通用HTTP请求类,很好用!

现在的移动应用几乎没有只在本地进行操作的,或多或少会有一定的网络请求,不论是普通的HTTP请求返回XML或JSON还是利用Socket进行TCP/UDP通信,Windows Phone上提供了,HttpWebRequest、WebClient、Socket等基本的通信类,但每次在请求的时候需要写一系列的代码,有时候还容易出错,下面介绍一个我个人在开发过程中觉得很好用的一个类,支持基本的GET和POST方法。


public class UniRequest
    {
        public delegate void HandleResult(string result);
        private HandleResult handle;

        HttpWebRequest request;

        HttpWebResponse response;

        Dictionary<string, object> Params = new Dictionary<string, object>();

        byte[] POSTBin;

        string ResponseContent;

        /// <summary>
        /// 构造函数,获取URL、方法
        /// </summary>
        /// <param name="url">请求路径</param>
        /// <param name="method">请求方法POST或GET</param>
        public UniRequest(string url, string method = "GET")
        {
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(url);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Request Created Failed!" + e.Message);
                return;
            }
            switch (method)
            {
                case "POST":
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    break;
                case "GET": request.Method = "GET"; break;
                default: request.Method = "GET"; break;
            }
        }

        /// <summary>
        /// 添加请求参数
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public void AddParams(string key, object value)
        {
            if (request.Method == "GET")
            {
                Debug.WriteLine("Method Error!");
                return;
            }
            Params.Add(key, value);
        }

        /// <summary>
        /// 开始请求
        /// </summary>
        /// <param name="handle">请求结果</param>
        public void StartRequest(HandleResult handle)
        {
            this.handle = handle;
            switch (request.Method)
            {
                default:
                case "GET": request.BeginGetResponse(new AsyncCallback(GetResponse), request); break;
                case "POST": request.BeginGetRequestStream(new AsyncCallback(UploadParam), request); break;
            }
        }

        void UploadParam(IAsyncResult result)
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            using (Stream stream = request.EndGetRequestStream(result))
            {
                string tmp = "";
                for (int i = 0; i < Params.Count; i++)
                {
                    tmp += string.Format("{0}={1}", Params.ElementAtOrDefault(i).Key, Params.ElementAtOrDefault(i).Value);
                    if (i + 1 != Params.Count)
                    {
                        tmp += "&";
                    }
                }
                POSTBin = Encoding.UTF8.GetBytes(tmp);
                stream.Write(POSTBin, 0, POSTBin.Length);
            }
            request.BeginGetResponse(new AsyncCallback(GetResponse), request);
        }

        void GetResponse(IAsyncResult result)
        {
            try
            {
                request = (HttpWebRequest)result.AsyncState;
                response = (HttpWebResponse)request.EndGetResponse(result);
                using (Stream stream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(stream);
                    ResponseContent = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                ResponseContent = "Request Error!";
                Debug.WriteLine(e.InnerException.ToString());
            }
            Deployment.Current.Dispatcher.BeginInvoke(() => { handle(ResponseContent); });
        }
    }


每次在请求的时候,只需要实例化一个对象,然后添加参数,即可开始异步请求,就像这样

   UniRequest Request = new UniRequest("url", "POST");
            Request.AddParams("Email", "Email"); //参数1
            Request.AddParams("Name", "Name"); //参数2
            Request.AddParams("Sex", "0"); //参数3
            Request.AddParams("Password", "123456"); //参数4
            Request.StartRequest(result =>
                {
                    MessageBox.Show(result);  //显示结果
                });

非常的方便!

你可能感兴趣的:(http,windows,实用,请求,phone,通用类)