Windows phone开发之Http请求访问篇

上一篇文章,提到了我参与的Windows Phone的第一个项目,我的准备工作,或者说技术储备吧!我个人做项目,比较喜欢将服务层都写好后,才开始界面UI的开发,这个项目也毫不例外,当然,我会写一些简单的界面,比如一个按钮来发起请求,来测试我的Http请求服务类。


上面这截图来自于MSDN,.net开发我比较喜欢查找资源的网站,用这个我们就能实现HTTP的访问了。

1、创建HttpWebRequest对象

this.Request = WebRequest.Create(this.Url)as HttpWebRequest;


2、设置Http请求的方式

this.Request.Method = this.Method;


3、根据Http请求的方式设置需要发送给服务器的数据,当然所谓的Post与Get的区别就不用赘述了吧!

如果是Get请求,参数都在URL上了,但是Post请求,我们此时就需要设置PostData了,代码如下:

this.Request.BeginGetRequestStream(SetPostData,this.Request);

if (Method.ToUpper() == Macro.POST)

                    {

                        this.Request.BeginGetRequestStream(SetPostData,this.Request);

                    }

                    else

                    {

                        this.Request.BeginGetResponse(GetReponse,this.Request);

                    }

注:Macro为我定义的常量类

/// <summary>

        /// 设置需要上传给服务器的数据

        /// </summary>

        /// <param name="result"></param>

        void SetPostData(IAsyncResult result)

        {

            try

            {

                this.Request = result.AsyncStateas HttpWebRequest;

                using (Stream stream =this.Request.EndGetRequestStream(result))

                {

                    if (!string.IsNullOrEmpty(this.Json))

                    {

                        byte[] buffer = Encoding.UTF8.GetBytes(this.Json);

                        stream.Write(buffer, 0, buffer.Length);

                    }

                }

                this.Request.BeginGetResponse(GetReponse,this.Request);

            }

            catch (Exception ex)

            {

                Debug.WriteLine(string.Format("HttpService SetPostData --->{0}", ex.Message));

            }

        }


设置处理返回数据的函数:

/// <summary>

        /// 处理http响应

        /// </summary>

        /// <param name="result">http应答结果</param>

        void GetReponse(IAsyncResult result)

        {

            try

            {

                string responseContent = "";

                this.Request = result.AsyncStateas HttpWebRequest;

                this.Response = this.Request.EndGetResponse(result) as HttpWebResponse;

                using (Stream stream =this.Response.GetResponseStream())

                {

                    StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));

                    responseContent = reader.ReadToEnd();

                }

                Deployment.Current.Dispatcher.BeginInvoke(() => {this.Handle(responseContent); });

            }

            catch (Exception ex)

            {

                Debug.WriteLine(string.Format("HttpService GetReponse --->{0}", ex.Message));

            }

        } 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值