silverlight与WebRequest通信
时间:2011-03-24 来源:YLWS
客户端代码
using System.IO; namespace webrequest { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } //定义异步委托方法 delegate void DispatcherInvoke(string str); private void button1_Click(object sender, RoutedEventArgs e) { //Url地址(必须是绝对地址) string url = "http://localhost:53822/timeHandler.ashx?day=10"; //创建WebRequest对象 WebRequest request = HttpWebRequest.Create(new Uri(url, UriKind.Absolute)); //请求类型 request.Method = "GET"; //开始获取响应并进行异步回调 request.BeginGetResponse(new AsyncCallback(responseReady), request); //其请求是异步回调方式的,从BeginGetResponse开始,并通过AsyncCallback指定回调方法; } public void responseReady(IAsyncResult ar) { WebRequest resquest = ar.AsyncState as WebRequest; WebResponse response = resquest.EndGetResponse(ar); //直接读取将发生跨线程错误:跨域线程访问无效 //using (Stream stream = response.GetResponseStream()) //{ // StreamReader reader = new StreamReader(stream); // MessageBox.Show(reader.ReadToEnd()); //} //因为其回调不是UI线程,所以不能直接对UI进行操作,这里使用Dispatcher.BeginInvoke()异步执行委托方法 Dispatcher.BeginInvoke(() => { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream); MessageBox.Show(reader.ReadToEnd()); } }); } } }
服务端参照:silverlight与WebClient通信
相关阅读 更多 +