2 WebClient与HttpWebRequest使用实例 * 首先创建一个Silverlight应用程序DevDivNetworking * 打开MainPage.xaml,添加3个Image控件
- <Image Height="60" HorizontalAlignment="Left" Margin="6,18,0,0" Name="webClientImage" Stretch="Fill" VerticalAlignment="Top" Width="60" />
- <Image Height="60" HorizontalAlignment="Left" Margin="9,174,0,0" Name="httpRequestImage" Stretch="Fill" VerticalAlignment="Top" Width="60" />
- <Image Height="60" HorizontalAlignment="Left" Margin="12,342,0,0" Name="imagesourceImage" Stretch="Fill" VerticalAlignment="Top" Width="60" Source="http://www.devdiv.com/bbs/forumimage/wp.jpg"/>
复制代码
其中webClientImage用来显示WebClient请求返回的图片, httpRequestImage用来显示HttpWebRequest返回的图片, 而imagesourceImage图片,我们直接设置它的Source指向一个网络图片地址,不需要我们自己来下载,程序执行的时候自动下载,下载完成以后自动更新Image控件,它直接封装了下载和更新过程,和我们即为webClientImage和httpRequestImage做的事情是一样的。 * 打开MainPage.xaml.cs文件,添加以下代码:
- private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
- {
- // WebClient request
- WebClient webClient = new WebClient(); webClient.OpenReadCompleted += OnWebClientOpenReadCompleted;
- webClient.OpenReadAsync(new Uri("http://www.devdiv.com/bbs/forumimage/wp.jpg"));
- // HttpWebRequest
- string url = "http://www.devdiv.com/bbs/forumimage/wp.jpg";
- WebRequest request = HttpWebRequest.Create(url);
- IAsyncResult result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
- }
- // WebClient request callback
- void OnWebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs args)
- {
- if (!args.Cancelled && args.Error == null)
- {
- BitmapImage bmp = new BitmapImage();
- bmp.SetSource(args.Result);
- webClientImage.Source = bmp;
- }
- }
- // HttpWebRequest callback
- private void ResponseCallback(IAsyncResult result)
- {
- HttpWebRequest request = (HttpWebRequest)result.AsyncState;
- WebResponse response = request.EndGetResponse(result);
- Dispatcher.BeginInvoke(() =>
- {
- BitmapImage bmp2 = new BitmapImage();
- bmp2.SetSource(response.GetResponseStream());
- httpRequestImage.Source = bmp2;
- });
- }
复制代码
我们来解释一下代码, PhoneApplicationPage_Loaded是页面加载后执行的代码,它发起了两个网络请求,一个是WebClient,一个是HttpWebRequest,做的事情都是一样,都是取网络下载一章图片。 OnWebClientOpenReadCompleted是在WebClient请求返程以后执行的回调函数,这里我们设置了webClientImage指向的图片 ResponseCallback是HttpWebRequest请求的回调函数,同样我们这里设置了httpRequestImage的图片。 大家可能已经注意到了,ResponseCallback并没有直接更新Image控件,而是通过了Dispatcher来实现的,这是因为HttpWebRequest的回调函数是在单独线程中执行的,而不是在主线程中执行 |