WindowsPhone与服务器通信

与其他平台一样,WindowsPhone与服务器通信有两种方式:

1.Socket方式:主要用在需要长链接的应用里边,上传文件等IO操作时使用

2.http方式:绝大多数应用采用的方式,通过访问服务器接口,解析服务器返回的json或者xml等数据

本文主要介绍http方式

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows;

namespace Phone.Common
{
    public class Http
    {
        public Http(HandleResult handle)
        {
            this.handle = handle;
        }

        public delegate void HandleResult(string result);
        private HandleResult handle;

        public void StartRequest(string Url)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Method = "GET";
            try
            {
                new Thread(() => webRequest.BeginGetResponse(new AsyncCallback(HandleResponse), webRequest)).Start();
            }
            catch
            {
            }
        }

        public void HandleResponse(IAsyncResult asyncResult)
        {

            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            string result = string.Empty;
            try
            {
                httpRequest = (HttpWebRequest)asyncResult.AsyncState;
                httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(asyncResult);

                using (var reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch
            {

            }
            finally
            {
                if (httpRequest != null) httpRequest.Abort();
                if (httpResponse != null) httpResponse.Close();
            }

            Deployment.Current.Dispatcher.BeginInvoke(() => handle(result));
        }
    }
}

 

posted on 2012-12-27 18:13  菜鸟的春天  阅读(466)  评论(0编辑  收藏  举报

导航