Windows Phone 7 网络编程之webclient和httpwebrequest的使用

 

Windows Phone 7 网络编程之webclient和httpwebrequest的使用

一、WebClient类和HttpWebRequest 类
System.Net.WebClient 类
提供向 URI 标识的资源发送数据和从 URI 标识的资源接收数据的公共方法。


WebClient 类提供向 URI(支持以 http:、https:、ftp:、和 file: 方案标识符开头的 URI) 标识的任何本地、Intranet 或 Internet 资源发送数据以及从这些资源接收数据的公共方法。

WebClient 类使用 WebRequest 类提供对资源的访问。WebClient 实例可以通过任何已向 WebRequest.RegisterPrefix 方法注册的 WebRequest 子代访问数据。

WebClient 类的方法、属性和事件


System.Net.HttpWebRequest
提供 WebRequest 类的 HTTP 特定的实现。

HttpWebRequest 对 HTTP 协议进行了完整的封装,程序使用 HTTP 协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成。
   HttpWebRequest常用命令如下:

  HttpWebRequest - 对指定的 URI 发出请求
  Create() - 初始化一个 WebRequest
  BeginGetResponse() - 开始对指定 URI 资源做异步请求
  EndGetResponse() - 结束对指定 URI 资源做异步请求
  HttpWebResponse - 对指定的 URI 做出响应
  GetResponseStream() - 获取响应的数据流   需要注意的是: HttpWebRequest使用基于代理的异步编程模型,在HTTP响应返回时引发的HttpWebRequest回调不是在UI线程上返回的,因此在该回调中需要额外代码处理UI,否则就会产生"跨线程访问无效"错误。

HttpWebRequest 类的方法、属性和事件

 

二、HttpWebRequest和WebClient的区别
1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Create();
2,其Method指定了请求类型,这里用的GET,还有POST;也可以指定ConentType;
3,其请求的Uri必须是绝对地址;
4,其请求是异步回调方式的,从BeginGetResponse开始,并通过AsyncCallback指定回调方法;
5,WebClient方式使用基于事件的异步编程模型,在HTTP响应返回时引发的WebClient回调是在UI线程中调用的,因此可用于更新UI元素的属性,例如把HTTP响应中的数据绑定到UI的指定控件上进行显示。HttpWebRequest是基于后台进程运行的,回调不是UI线程,所以不能直接对UI进行操作,通常使用Dispatcher.BeginInvoke()跟界面进行通讯。

 

扫描二维码关注公众号,回复: 5119995 查看本文章

二、HttpWebRequest和WebClient在Windows Phone 7上的实例

  获取网页的源代码


 

 

 
     
<phone:PhoneApplicationPage x:Class="WebClientHttpWebRequest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded"> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="q" Text="加菲猫的博客" Style="{StaticResource PhoneTextNormalStyle}" Height="39" Width="444" /> </StackPanel> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Height="38" HorizontalAlignment="Left" Margin="12,6,0,0" Name="webClientTextBlock" Text="TextBlock" VerticalAlignment="Top" Width="438" /> <TextBlock Height="44" HorizontalAlignment="Left" Margin="9,266,0,0" Name="httpWebRequestTextBlock" Text="TextBlock" VerticalAlignment="Top" Width="438" /> <TextBox Height="210" HorizontalAlignment="Left" Margin="9,50,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="438" /> <TextBox Height="239" HorizontalAlignment="Left" Margin="12,316,0,0" Name="textBox2" Text="TextBox" VerticalAlignment="Top" Width="444" /> </Grid> </Grid> </phone:PhoneApplicationPage>



 
     
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.IO; namespace WebClientHttpWebRequest { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { DoWebClient(); DoHttpWebRequest(); } private void DoWebClient() { WebClient webClient = new WebClient(); webClient.OpenReadAsync(new Uri("http://www.cnblogs.com/linzheng"));//在不阻止调用线程的情况下,从资源返回数据 webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);//异步操作完成时发生 } void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { using (StreamReader reader = new StreamReader(e.Result)) { string contents = reader.ReadToEnd(); int begin = contents.ToString().IndexOf("<title>"); int end = contents.ToString().IndexOf("</title>"); string note = contents.Substring(contents.ToString().IndexOf("摘要"), 300); webClientTextBlock.Text = contents.ToString().Substring(begin+7, end - begin-7); textBox1.Text = note; } } private void DoHttpWebRequest() { string url = "http://www.cnblogs.com/linzheng"; WebRequest request = HttpWebRequest.Create(url);//创建WebRequest类 IAsyncResult result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);//返回异步操作的状态 } private void ResponseCallback(IAsyncResult result) { HttpWebRequest request = (HttpWebRequest)result.AsyncState;//获取异步操作返回的的信息 WebResponse response = request.EndGetResponse(result);//结束对 Internet 资源的异步请求 using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string contents = reader.ReadToEnd(); int begin = contents.ToString().IndexOf("<title>"); int end = contents.ToString().IndexOf("</title>"); string note = contents.Substring(contents.ToString().IndexOf("摘要"), 300); //通过呼叫UI Thread来改变页面的显示 Dispatcher.BeginInvoke(() => { httpWebRequestTextBlock.Text = contents.ToString().Substring(begin + 7, end - begin - 7); textBox2.Text = note; }); } } } }

猜你喜欢

转载自blog.csdn.net/snowson/article/details/6778797