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()跟界面进行通讯。

 

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

获取网页的源代码

 

 

 

 
  1. <phone:PhoneApplicationPage   
  2.   x:Class="WebClientHttpWebRequest.MainPage" 
  3.   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  4.   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5.   xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
  6.   xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
  7.   xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  8.   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  9.   mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" 
  10.   FontFamily="{StaticResource PhoneFontFamilyNormal}" 
  11.   FontSize="{StaticResource PhoneFontSizeNormal}" 
  12.   Foreground="{StaticResource PhoneForegroundBrush}" 
  13.   SupportedOrientations="Portrait" Orientation="Portrait" 
  14.   shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded"> 
  15.     <Grid x:Name="LayoutRoot" Background="Transparent"> 
  16.         <Grid.RowDefinitions> 
  17.             <RowDefinition Height="Auto"/> 
  18.             <RowDefinition Height="*"/> 
  19.         </Grid.RowDefinitions> 
  20.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 
  21.             <TextBlock x:Name="q" Text="加菲猫的博客" Style="{StaticResource PhoneTextNormalStyle}" Height="39" Width="444" />    
  22.         </StackPanel> 
  23.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
  24.             <TextBlock Height="38" HorizontalAlignment="Left" Margin="12,6,0,0" Name="webClientTextBlock" Text="TextBlock" VerticalAlignment="Top" Width="438" /> 
  25.             <TextBlock Height="44" HorizontalAlignment="Left" Margin="9,266,0,0" Name="httpWebRequestTextBlock" Text="TextBlock" VerticalAlignment="Top" Width="438" /> 
  26.             <TextBox Height="210" HorizontalAlignment="Left" Margin="9,50,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="438" /> 
  27.             <TextBox Height="239" HorizontalAlignment="Left" Margin="12,316,0,0" Name="textBox2" Text="TextBox" VerticalAlignment="Top" Width="444" /> 
  28.         </Grid> 
  29.     </Grid> 
  30. </phone:PhoneApplicationPage> 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Windows;  
  6. using System.Windows.Controls;  
  7. using System.Windows.Documents;  
  8. using System.Windows.Input;  
  9. using System.Windows.Media;  
  10. using System.Windows.Media.Animation;  
  11. using System.Windows.Shapes;  
  12. using Microsoft.Phone.Controls;  
  13. using System.IO;  
  14.  
  15. namespace WebClientHttpWebRequest  
  16. {  
  17.     public partial class MainPage : PhoneApplicationPage  
  18.     {  
  19.         public MainPage()  
  20.         {  
  21.             InitializeComponent();  
  22.         }  
  23.         private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)  
  24.         {  
  25.             DoWebClient();  
  26.             DoHttpWebRequest();  
  27.         }  
  28.         private void DoWebClient()  
  29.         {  
  30.             WebClient webClient = new WebClient();  
  31.             webClient.OpenReadAsync(new Uri("http://www.cnblogs.com/linzheng"));//在不阻止调用线程的情况下,从资源返回数据  
  32.             webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);//异步操作完成时发生  
  33.         }  
  34.         void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)  
  35.         {  
  36.             using (StreamReader reader = new StreamReader(e.Result))  
  37.             {  
  38.                 string contents = reader.ReadToEnd();  
  39.                 int begin = contents.ToString().IndexOf("<title>");  
  40.                 int end = contents.ToString().IndexOf("</title>");  
  41.                 string note = contents.Substring(contents.ToString().IndexOf("摘要"), 300);  
  42.                 webClientTextBlock.Text = contents.ToString().Substring(begin+7, end - begin-7);  
  43.                 textBox1.Text = note;  
  44.             }  
  45.  
  46.         }  
  47.         private void DoHttpWebRequest()  
  48.         {  
  49.             string url = "http://www.cnblogs.com/linzheng";  
  50.             WebRequest request = HttpWebRequest.Create(url);//创建WebRequest类  
  51.             IAsyncResult result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);//返回异步操作的状态  
  52.         }  
  53.         private void ResponseCallback(IAsyncResult result)  
  54.         {  
  55.             HttpWebRequest request = (HttpWebRequest)result.AsyncState;//获取异步操作返回的的信息  
  56.             WebResponse response = request.EndGetResponse(result);//结束对 Internet 资源的异步请求  
  57.  
  58.             using (Stream stream = response.GetResponseStream())  
  59.             using (StreamReader reader = new StreamReader(stream))  
  60.             {  
  61.                 string contents = reader.ReadToEnd();  
  62.                 int begin = contents.ToString().IndexOf("<title>");  
  63.                 int end = contents.ToString().IndexOf("</title>");  
  64.                 string note = contents.Substring(contents.ToString().IndexOf("摘要"), 300);  
  65.                 //通过呼叫UI Thread来改变页面的显示  
  66.                 Dispatcher.BeginInvoke(() => { httpWebRequestTextBlock.Text = contents.ToString().Substring(begin + 7, end - begin - 7); textBox2.Text = note; });  
  67.  
  68.             }  
  69.         }  
  70.     }  

 

本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1078703



相关文章
|
3月前
|
缓存 网络协议 数据安全/隐私保护
[运维笔记] - (命令).Windows server常用网络相关命令总结
[运维笔记] - (命令).Windows server常用网络相关命令总结
191 0
|
1月前
|
Linux iOS开发 MacOS
|
1月前
|
缓存 网络协议 Unix
Windows 命令提示符(CMD)操作(四):网络通信
Windows 命令提示符(CMD)操作(四):网络通信
62 0
|
6月前
|
网络协议 程序员 API
[笔记] Microsoft Windows网络编程《一》WinSock简介(四)
[笔记] Microsoft Windows网络编程《一》WinSock简介(四)
|
4月前
|
网络协议 关系型数据库 网络虚拟化
Windows网络服务综测刷题
Windows网络服务综测刷题
26 0
|
6月前
|
人工智能 网络协议 API
[笔记] Microsoft Windows网络编程《三》网际协议(三)
[笔记] Microsoft Windows网络编程《三》网际协议(三)
|
6月前
|
人工智能 网络协议 API
[笔记] Microsoft Windows网络编程《三》网际协议(二)
[笔记] Microsoft Windows网络编程《三》网际协议(二)
|
6月前
|
网络协议 API 网络架构
[笔记] Microsoft Windows网络编程《三》网际协议(一)
[笔记] Microsoft Windows网络编程《三》网际协议
|
6月前
|
网络协议 API 网络性能优化
[笔记] Microsoft Windows网络编程《二》设计Winsock
[笔记] Microsoft Windows网络编程《二》设计Winsock
|
6月前
|
网络协议 程序员 API
[笔记] Microsoft Windows网络编程《一》WinSock简介(三)
[笔记] Microsoft Windows网络编程《一》WinSock简介(三)