WindowsPhone网络编程之Client
System.Net通信方式
1 HttpWebRequest使用基于代理的异步编程模型,而WebClient使用的是基于事件的异步编程模型,更容易使用,并且需要的代码量通常比较上。
2 HttpWebRequest支持HTTP协议的较大子集,这使其更适合一些高级方案,因为它提供对服务请求的更强控制,
3 在HTTP响应返回时,引发的WebClient回调实在用户界面ui线程中调用,因此可用于更新ui元素属性,而HttpWebRequest不是,因此回调中需要额外代码处理ui
WebClient类
由于WebClient请求都是异步的,使用的是基于异步事件编程模型,大部分交互操作都是依靠时间处理来完成,
DownloadProcessChanged
DownloadStringChanged
OpenReadCompleted
OpenWriteCompleted
UploadProcessChanged
UploadStringChanged
WriteStreamClosed
<phone:PhoneApplicationPage
x:Class="快递100.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">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>-->
<!--TitlePanel contains the name of the application and page title-->
<!--<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>-->
<!--ContentPanel - place additional content here-->
<!--<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>-->
<TextBlock Text="快递查询" FontSize="28" HorizontalAlignment="Center"></TextBlock>
<Button Content="查 询" Height="72" HorizontalAlignment="Left" Margin="150,155,0,0" Name="btnSearch" VerticalAlignment="Top" Width="160" Click="btnSearch_Click" />
<TextBox Height="71" HorizontalAlignment="Right" Margin="0,63,27,0" Name="textBox1" Text="" InputScope="TelephoneNumber" VerticalAlignment="Top" Width="303" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="61,84,0,0" Name="textBlock1" Text="快递单号:" VerticalAlignment="Top" />
<TextBlock Height="200" HorizontalAlignment="Left" Margin="12,327,0,0" Name="txtBlockNews" Text="" VerticalAlignment="Top" Width="468" />
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.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;
using System.IO.IsolatedStorage;
using System.Text;
using System.Xml;
namespace 快递100
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//throw new NotImplementedException();
NavigationService.Navigate(new Uri("/快递100;component/Page1.xaml", UriKind.Relative));
}
// IsolatedStorageFile isolatedStroageFile = null;
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
string uri = @"http://api.kuaidi100.com/apione?com=yuantong&nu=" + this.textBox1.Text + "&show=1 ";
WebClient scDownloadString = new WebClient();
scDownloadString.DownloadStringCompleted += new DownloadStringCompletedEventHandler(scDownloadString_DownloadStringCompleted);
scDownloadString.DownloadStringAsync(new Uri(uri));
}
void scDownloadString_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//throw new NotImplementedException();
string returnValue = e.Result ;
//this is source demo returnValue "{\"message\":\"ok\",\"status\":\"1\",\"link\":\"http://kuaidi100.com/chaxun?com=yuantong&nu=1780371398\",\"state\":\"3\",\"data\":[{\"time\":\"2012-03-19 15:02:42\",\"context\":\"河南省南阳市白河南/PDA正常签收扫描/签收人:孟星星 \"}]}" string
//source demo2 e.Result = "<xml><message>ok</message><status>1</status><link>http://kuaidi100.com/chaxun?com=yuantong&nu=1780371398</link><state>3</state><data><time>2012-03-19 15:02:42</time><context>河南省南阳市白河南/PDA正常签收扫描/签收人:孟星星 </context></data></xml>"
Dictionary<string,string> dictionary = new Dictionary<string, string>();
using (XmlReader xmlReader=XmlReader.Create(new StringReader(returnValue)))
{
while (xmlReader.Read())
{
//if this is the first node and name ==xml
if (xmlReader.IsStartElement()&&(xmlReader.LocalName=="xml"))
{
using (XmlReader itemReader=xmlReader.ReadSubtree())
{
while (itemReader.Read())
{
//如果找到一个节点就开始读取其中内容
if (itemReader.NodeType==XmlNodeType.Element)
{
string nodeName = itemReader.Name;
itemReader.Read();
//提取内容
if (itemReader.NodeType==XmlNodeType.Text)
{
switch (nodeName)
{
case "message":
dictionary.Add("message",itemReader.Value);break;
case "status":
dictionary.Add("status", itemReader.Value);break;
case "link":
dictionary.Add("link", itemReader.Value); break;
case "state":
dictionary.Add("state", itemReader.Value); break;
case "time":
dictionary.Add("time", itemReader.Value); break;
case "context":
dictionary.Add("context", itemReader.Value); break;
default:
break;
}
}
}
}
}
}
}
}
string str=null;
dictionary.TryGetValue("context", out str);
this.txtBlockNews.Text = str;
}
}
}
<phone:PhoneApplicationPage
x:Class="快递100.Page1"
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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>-->
<!--TitlePanel contains the name of the application and page title-->
<!--<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>-->
<!--ContentPanel - place additional content here-->
<!--<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>-->
<Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="144,64,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
<Image Height="427" HorizontalAlignment="Left" Margin="0,142,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="480" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="24,708,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="178,708,0,0" Name="textBlock2" Text="TextBlock" VerticalAlignment="Top" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="345,708,0,0" Name="textBlock3" Text="TextBlock" VerticalAlignment="Top" />
<ProgressBar Height="28" HorizontalAlignment="Left" Margin="12,608,0,0" Name="progressBar1" VerticalAlignment="Top" Width="439" />
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</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;
namespace 快递100
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string uri = @"http://img9.zol.com.cn/dp_800/390/389112.jpg";
WebClient wcDownloadStream = new WebClient();
if(wcDownloadStream.IsBusy)
{
wcDownloadStream.CancelAsync();
}
wcDownloadStream.OpenReadCompleted += new OpenReadCompletedEventHandler(wcDownloadStream_OpenReadCompleted);
wcDownloadStream.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadStream_DownloadProgressChanged);
wcDownloadStream.OpenReadAsync(new Uri(uri));
}
void wcDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//throw new NotImplementedException();
progressBar1.Value = e.ProgressPercentage;
textBlock1.Text = e.ProgressPercentage.ToString() + "%";
textBlock2.Text = e.BytesReceived.ToString();
textBlock3.Text = e.TotalBytesToReceive.ToString();
}
void wcDownloadStream_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// throw new NotImplementedException();
System.IO.Stream str = e.Result;
System.Windows.Media.Imaging.BitmapImage imageSource = new System.Windows.Media.Imaging.BitmapImage();
imageSource.SetSource(str);
image1.Source = imageSource;
}
}
}