Windows Phone 7的通信支持异步通信,在使用时,曾想尽方法来达到同步的效果,但均失败告终,所以还是按照它的设计来实现异步通信。
public void request() { //建立WebRequest HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.test.com")); //设置cookie CookieContainer contain = new CookieContainer(); contain.Add(webRequest.RequestUri, new Cookie("key", "value")); contain.Add(webRequest.RequestUri, new Cookie("key1", "value1")); webRequest.CookieContainer = contain; //设置请求方法 webRequest.Method = "GET"; //发出请求 webRequest.BeginGetResponse(new AsyncCallback(handleResponse), webRequest); } private void handleResponse(IAsyncResult asyncResult) { try { HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState; HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult); //得到响应流 Stream streamResult = webResponse.GetResponseStream(); //获得cookies,保存有HTTP response的状态信息. CookieCollection cookies=webResponse.Cookies; //得到与服务端响应相关联的Headers WebHeaderCollection headers = webResponse.Headers; String contentType = webResponse.ContentType; } catch (WebException) { } Dispatcher.BeginInvoke( () =>{ //对页面进行一些操作 }); }
在获得响应后,要改变前端界面时,需要使用异步委托机制。