windows phone 操作 http异步返回结果

wp中为了提升用户体验,砍掉了http的同步操作,仅支持http异步请求,那么该如何及时处理异步操作返回的结果。纠结了很久,终于在技术群中好友的帮助下解决了问题,借助事件,将异步编程模型模式简单的处理成类似webclient的事件异步模式(windows phone 7的)。

class Helper
    {
        public Action<string> DownLoadStringCompleted = null;

        public void HtmlGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.BeginGetResponse(asyn =>
            {
                var httpResult = (HttpWebRequest)asyn.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(asyn);
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string result = reader.ReadToEnd();

                    //处理返回的html
                    if (DownLoadStringCompleted != null)
                    {
                        DownLoadStringCompleted(result);
                    }
                };
            }, request);
        }
    }

之后变可以向使用WebClient的OpenReadAsync一样处理数据

 

windows phone 8 实现方式的改变

public class HttpHelper
    {
        public async Task<string> GetUrlContentAsync(string url)
        {
            var request = WebRequest.CreateHttp(url);
            string result;
            try
            {
                using (WebResponse response = await request.GetResponseAsync())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = await reader.ReadToEndAsync();
                    }
                }
            }
            catch (WebException webExc)
            {                
                throw webExc;
            }            

            return result;
        }

        //private HttpClient client; 

        public Task<HttpWebResponse> GetResponseAsync(HttpWebRequest request)
        {
            var taskComplete = new TaskCompletionSource<HttpWebResponse>();
            try
            {
                request.BeginGetResponse(asyncResponse =>
                {
                    HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
                    HttpWebResponse response = responseRequest.EndGetResponse(asyncResponse) as HttpWebResponse;
                    taskComplete.TrySetResult(response);
                }, request);
            }
            catch (WebException webExc)
            {
                HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
                taskComplete.TrySetResult(failedResponse);
            }
            return taskComplete.Task;
        }
    }    

 

posted on 2013-12-19 22:42  mayue-tzc  阅读(288)  评论(0编辑  收藏  举报