代码改变世界

silverlight系列(XML操作、HTTP通信、WebRequest通信)

2010-03-08 11:49  key_sky  阅读(1619)  评论(0编辑  收藏  举报

HTTP通信方案

  • 在同一域中下载和上传资源:使用WebClient类
  • 调用在同一域中承载的基于HTTP的Web服务:使用WebClient类或HttpWebRequest/HttpWebResponse类
  • 调用在同一域中承载的SOAP、WCF或ASP.NET AJAX Web服务:为Web服务调用生成的代理
  • 处理Web服务中的XML、JSON或RSS数据:使用WebClien类或HttpWebRequest/HttpWebResponse类
  • 调用另一域中的Web服务:确保客户端访问策略文件位于域的根。使用代理、WebClient类或HttpWebRequest/HttpWebResponse类
  • 发动PUT、DELETE和其他HTTP方法,包括自定义方法:确保客户端访问策略启动了其他HTTP方法。指定客户端HTTP处理并按正常方式使用HttpWebRequest/HttpWebResponse类
  • 对跨域POST请求设置请求标头:确保根据客户端访问策略文件允许标头。使用WebClient类
  • 随所有方法发送请求标头:指定客户端HTTP处理并按正常方式使用HttpWebRequest/HttpWebResponse类
  • 发送对返回错误代码和SOAP错误的SOAP服务的请求:指定客户端HTTP处理并按正常方式使用HttpWebRequest/HttpWebRespons类

跨域访问请将工程中crossdomain.xml复制到Web服务root根目录下.详细信息http://msdn.microsoft.com/zh-cn/library/cc838250(VS.95).aspx#crossdomain_communication

WebClient类:提供一个基于事件的简单模型,可以下载和上传留和字符串。

Methods:

  • CancelAsync:取消一个挂起的异步操作
  • DownloadStringAsync(Uri,Object):以字符串形式下载位于指定Uri的资源
  • OpenWriteAsync(Uri,String,Object):打开一个流以将数据写入指定的资源,这些方法不会阻止调用线程
  • UploadStringAsync(Uri,String,String,Object):将指定的字符串上传到指定的资源,这些方法不会阻止调用线程
  • GetWebRequest(Uri):返回一个WebRequest对象
  • GetWebResponse(WebRequest,IAsyncResult):使用指定的IAsyncResult异步操作获取
  • WebRequest的WebResponse
  • OpenReadAsync(Uri,Object):打开流向指定资源的可读流

Properties:

  • AllowReadStreamBuffering:获取或设置是否对从某一WebClient实例的资源读取的数据进行缓冲处理
  • BaseAddress:获取或设置WebClient发出请求的URI。如果未指定任何基址,则将该属性将被初始化为应用程序来源
  • Credentials:获取或设置发送到主机并用于对请求进行身份验证的网络凭据
  • Encoding:获取或设置用于下载和上载字符串的字符编码
  • Headers:获取或设置与请求关联的标头名称/值对集合
  • IsBusy:获取Web请求是否在进行中
  • ResponseHeaders:获取与响应关联的标头名称/值对集合

Events:

  • DownloadProgressChanged:在异步下载操作成功传输部分或全部数据后发生
  • DownloadStringCompleted:在异步资源下载操作完成时发生
  • OpenReadCompleted:在异步资源读取操作完成时发生
  • UploadProgressChanged:在异步上载操作成功转换部分或全部数据后发生
  • UploadStringCompleted:在异步字符串上完成时发生
  • WriteStreamClosed:在异步写入流操作完成时发生

二、HttpWebRequest

Methods:

  • Abort:取消对Internet资源的请求
  • BeginGetRequestStream:开始对用来写入数据的Stream对象的异步请求
  • BeginGetResponse:开始对Internet资源的异步请求
  • EndRequestStream:结束对用于写入数据的Stream对象的异步请求
  • EndGetResponse:结束对Internet资源的异步请求
  • Accept:获取或设置Accept HTTP标头的值
  • AllowReadStreamBuffering:获取或设置是否对从Internet读取的资源读取的数据进行缓冲处理
  • ContentType:获取或设置Content-type HTTP标头的值
  • CookidContainer:指定与HTTP请求相关联的CookieCollection对象的集合
  • HaveResponse:获取是否收到了来自Internet资源的响应值
  • Headers:指定构成HTTP标头的名称/值对的集合
  • Method:获取或设置请求的方法
  • RequestUri:获取请求的原始统一资源标识符(URI)
  • Cookies:获取用于保存HTTP响应的状态信息的cookie
  • Method:获取用于返回响应的方法
  • StatusCode:获取响应的状态
  • StatusDescription:获取与响应一起返回的状态说明

XML.xaml:

<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="155"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock x:Name="tb1" TextWrapping="Wrap" Foreground="Green" Grid.Row="0"></TextBlock>
<TextBlock x:Name="tb2" TextWrapping="Wrap" Foreground="Red" Grid.Row="1"></TextBlock>
</Grid>

XML.CS:

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 System.Xml;
13  using System.IO;
14  using System.Text;
15  using System.IO.IsolatedStorage;
16
17  namespace XMLWriter_XmlReader
18 {
19 public partial class MainPage : UserControl
20 {
21 string strxml = string.Empty;
22 public MainPage()
23 {
24 InitializeComponent();
25 CreateXML();
26 ReadXML();
27 OperateIsolatedStorageFile();
28 }
29 private void CreateXML()
30 {
31 strxml = @" <employee Total='320' compony='BJYD'>
32 <name>keysky</name>
33 <old>24</old>
34 <birthPlace>安徽</birthPlace>
35 <selfinfo>Sports,Programming</selfinfo>
36 </employee>";
37 }
38 private void ReadXML()
39 {
40 StringBuilder xml = new StringBuilder();
41 using (XmlReader xmlread = XmlReader.Create(new StringReader(strxml)))
42 {
43 xmlread.ReadToFollowing("employee");//找到需要获取的元素节点
44   xmlread.MoveToAttribute(1);//读取索引第一个属性
45   xml.AppendLine("公司名称:" + xmlread.Value);
46 xmlread.ReadToFollowing("name");
47 xml.AppendLine("name:" + xmlread.ReadElementContentAsString());
48 xmlread.ReadToFollowing("selfinfo");
49 xml.AppendLine("selfinfo:" + xmlread.ReadElementContentAsString());
50 }
51 tb1.Text = xml.ToString();
52 }
53 private void OperateIsolatedStorageFile()
54 {
55 using (IsolatedStorageFile StorageFile = IsolatedStorageFile.
56 GetUserStoreForApplication())
57 //获取主机独立存储区
58   {
59 using (IsolatedStorageFileStream StorageStream = new
60 IsolatedStorageFileStream("Storage.xml",
61 FileMode.Create, StorageFile))
62 //创建并初始化独立存储流
63   {
64 XmlWriterSettings settings = new XmlWriterSettings();//初始化xmlwriter
65   settings.Indent = true;//元素自动缩进
66   using (XmlWriter writer = XmlWriter.Create(StorageStream, settings))
67 {
68 writer.WriteComment("Storage XML Document");//写入xml文本注释
69   writer.WriteStartElement("Employee");//写入开始标记
70   writer.WriteAttributeString("Compony", "BJYD");//写入标记属性
71   writer.WriteAttributeString("Total", "320");
72 writer.WriteStartElement("name");//写入开始元素标记
73   writer.WriteString("keysky");//写入元素字符串
74   writer.WriteEndElement();//关闭元素命名空间
75  
76 writer.WriteStartElement("selfinfo");
77 writer.WriteString("Sports,Programming");
78 writer.WriteEndElement();
79
80 writer.Flush();//刷新数据流
81   }
82 }
83
84 using (StreamReader sr = new StreamReader(StorageFile.OpenFile
85 ("Storage.xml", FileMode.Open)))
86 {
87 tb2.Text = sr.ReadToEnd();
88 }
89 StorageFile.DeleteFile("Storage.xml");//删除独立存储区的文件
90   }
91 }
92
93 }
94 }
95  

运行效果:

WebClient.xaml:

<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" Width="Auto" Height="500"
ShowGridLines
="False" VerticalAlignment="Top" Margin="5,5,5,5">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button x:Name="btn1" Height="25" Width="85" Content="上 传" Click="btn1_Click" Grid.Row="0"
Grid.Column
="0" Margin="5" HorizontalAlignment="Left" ></Button>
<Button x:Name="btn2" Height="25" Width="85" Content="下 载" Click="btn2_Click" Grid.Row="0"
Grid.Column
="1" Margin="5" HorizontalAlignment="Left" ></Button>
<TextBlock TextWrapping="NoWrap" Height="Auto" Foreground="Green" x:Name="tb1" Grid.Row="1"
Grid.Column
="0" Margin="5" Width="250"></TextBlock>
<TextBlock TextWrapping="NoWrap" Height="Auto" Foreground="Blue" x:Name="tb2" Grid.Row="1"
Grid.Column
="1" Margin="5" Width="250"></TextBlock>
<TextBlock TextWrapping="NoWrap" Height="Auto" Foreground="Red" x:Name="tb3" Grid.Row="2"
Grid.Column
="0" Margin="5" Width="250"></TextBlock>
<TextBlock TextWrapping="NoWrap" Height="Auto" Foreground="HotPink" x:Name="tb4" Grid.Row="2"
Grid.Column
="1" Margin="5" Width="250"></TextBlock>
</Grid>
<!--
HTTP通信方案
1.在同一域中下载和上传资源:使用WebClient类
2.调用在同一域中承载的基于HTTP的Web服务:使用WebClient类或HttpWebRequest
/HttpWebResponse类
3.调用在同一域中承载的SOAP、WCF或ASP.NET AJAX Web服务:为Web服务调用生成的代理
4.处理Web服务中的XML、JSON或RSS数据:使用WebClien类或HttpWebRequest/HttpWebResponse类
5.调用另一域中的Web服务:确保客户端访问策略文件位于域的根。使用代理、
WebClient类或HttpWebRequest/HttpWebResponse类
6.发动PUT、DELETE和其他HTTP方法,包括自定义方法:确保客户端访问策略启动了
其他HTTP方法。指定客户端HTTP处理
并按正常方式使用HttpWebRequest/HttpWebResponse类
7.对跨域POST请求设置请求标头:确保根据客户端访问策略文件允许标头。使用WebClient类
8.随所有方法发送请求标头:指定客户端HTTP处理并按正常方式使用HttpWebRequest/
HttpWebResponse类
9.发送对返回错误代码和SOAP错误的SOAP服务的请求:指定客户端HTTP处理并按
正常方式使用HttpWebRequest/HttpWebRespons类

跨域访问请将工程中crossdomain.xml复制到Web服务root根目录下
详细信息http://msdn.microsoft.com/zh-cn/library/cc838250(VS.95).aspx#
crossdomain_communication

WebClient类:提供一个基于事件的简单模型,可以下载和上传留和字符串。
Methods:
CancelAsync:取消一个挂起的异步操作
DownloadStringAsync(Uri,Object):以字符串形式下载位于指定Uri的资源
OpenWriteAsync(Uri,String,Object):打开一个流以将数据写入指定的资源,
这些方法不会阻止调用线程
UploadStringAsync(Uri,String,String,Object):将指定的字符串上传到指定的资源,
这些方法不会阻止调用线程
GetWebRequest(Uri):返回一个WebRequest对象
GetWebResponse(WebRequest,IAsyncResult):使用指定的IAsyncResult异步操作获取
WebRequest的WebResponse
OpenReadAsync(Uri,Object):打开流向指定资源的可读流
Properties:
AllowReadStreamBuffering:获取或设置是否对从某一WebClient实例的资源读取的数据
进行缓冲处理
BaseAddress:获取或设置WebClient发出请求的URI。如果未指定任何基址,则将该属性
将被初始化为应用程序来源
Credentials:获取或设置发送到主机并用于对请求进行身份验证的网络凭据
Encoding:获取或设置用于下载和上载字符串的字符编码
Headers:获取或设置与请求关联的标头名称/值对集合
IsBusy:获取Web请求是否在进行中
ResponseHeaders:获取与响应关联的标头名称/值对集合
Events:
DownloadProgressChanged:在异步下载操作成功传输部分或全部数据后发生
DownloadStringCompleted:在异步资源下载操作完成时发生
OpenReadCompleted:在异步资源读取操作完成时发生
UploadProgressChanged:在异步上载操作成功转换部分或全部数据后发生
UploadStringCompleted:在异步字符串上完成时发生
WriteStreamClosed:在异步写入流操作完成时发生
-->

 

WebClient.cs:

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
13 namespace CommunicationOfWebclient
14 {
15 public partial class MainPage : UserControl
16 {
17 WebClient client = new WebClient();
18 public MainPage()
19 {
20 InitializeComponent();
21 client.UploadStringCompleted += new
22 UploadStringCompletedEventHandler(uploadStrCompleted);
23 client.UploadProgressChanged += new
24 UploadProgressChangedEventHandler(uploadProgress);
25 client.DownloadStringCompleted += new
26 DownloadStringCompletedEventHandler(downloadStrCompleted);
27 client.DownloadProgressChanged += new
28 DownloadProgressChangedEventHandler(downloadProgress);
29 }
30 private void uploadStrCompleted(object sender, UploadStringCompletedEventArgs e)
31 {
32 if (e.Error != null) MessageBox.Show(e.Error.Message);
33 else tb1.Text = e.Result;//获取服务器回复
34 }
35
36 private void uploadProgress(object sender, UploadProgressChangedEventArgs e)
37 {
38 tb2.Text = "上传完成百分比:" + e.ProgressPercentage.ToString()
39 + " 上传字节数:" + e.BytesSent.ToString();
40 //获取下载百分比和字节数
41 }
42
43 private void btn1_Click(object sender, RoutedEventArgs e)
44 {
45 string strpost = @" <employee Total='320' compony='BJYD'>
46 <name>keysky</name>
47 <old>24</old>
48 <birthPlace>安徽</birthPlace>
49 <selfinfo>Sports,Programming</selfinfo>
50 </employee>";
51 client.UploadStringAsync(new Uri("http://localhost/engin/info.asp",
52 UriKind.Absolute), strpost);
53 }
54
55 private void btn2_Click(object sender, RoutedEventArgs e)
56 {
57 client.DownloadStringAsync(new Uri("http://localhost/engin/info.asp",
58 UriKind.Absolute));
59 }
60
61 private void downloadStrCompleted(object sender, DownloadStringCompletedEventArgs e)
62 {
63 if (e.Error != null) MessageBox.Show(e.Error.Message);
64 else tb3.Text = e.Result;
65 }
66
67 private void downloadProgress(object sender, DownloadProgressChangedEventArgs e)
68 {
69 tb4.Text = "下载完成百分比:" + e.ProgressPercentage.ToString()
70 + " 下载字节数:" + e.BytesReceived.ToString();
71 }
72 }
73 }
74

运行效果:

HttpWebRequest.xaml:

<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" Width="Auto" Height="500"
ShowGridLines
="False" VerticalAlignment="Top" Margin="5,5,5,5">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button x:Name="btnPost" Height="25" Width="85" Content="上 传" Click="btnPost_Click"
Grid.Row
="0" Grid.Column="0" Margin="5" HorizontalAlignment="Left" ></Button>
<TextBlock TextWrapping="NoWrap" Height="Auto" Foreground="Green" x:Name="tb1"
Grid.Row
="1" Grid.Column="0" Margin="5" Width="Auto"></TextBlock>
</Grid>
<!--
HttpWebRequest
Methods:
1.Abort:取消对Internet资源的请求
2.BeginGetRequestStream:开始对用来写入数据的Stream对象的异步请求
3.BeginGetResponse:开始对Internet资源的异步请求
4.EndRequestStream:结束对用于写入数据的Stream对象的异步请求
5.EndGetResponse:结束对Internet资源的异步请求
Properties:
1.Accept:获取或设置Accept HTTP标头的值
2.AllowReadStreamBuffering:获取或设置是否对从Internet读取的资源读取的数据进行缓冲处理
3.ContentType:获取或设置Content-type HTTP标头的值
4.CookidContainer:指定与HTTP请求相关联的CookieCollection对象的集合
5.HaveResponse:获取是否收到了来自Internet资源的响应值
6.Headers:指定构成HTTP标头的名称/值对的集合
7.Method:获取或设置请求的方法
8.RequestUri:获取请求的原始统一资源标识符(URI)
HttpWebResponse
Properties:
1.Cookies:获取用于保存HTTP响应的状态信息的cookie
2.Method:获取用于返回响应的方法
3.StatusCode:获取响应的状态
4.StatusDescription:获取与响应一起返回的状态说明
-->

HttpWebRequest.cs:

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 System.Threading;
13 using System.IO;
14
15 namespace CommunicationOfWebRequestWebResponse
16 {
17 public partial class MainPage : UserControl
18 {
19 SynchronizationContext synContext;
20 string StatusString;
21 public MainPage()
22 {
23 InitializeComponent();
24 }
25
26 private void btnPost_Click(object sender, RoutedEventArgs e)
27 {
28 synContext = SynchronizationContext.Current;//获取当前线程上下文
29
30 HttpWebRequest request = WebRequest.Create(new Uri("http://localhost/engin/info.asp",
31 UriKind.Absolute)) as HttpWebRequest;
32 request.Method = "POST";//设置请求方法为POST
33
34 IAsyncResult asynResult = request.BeginGetRequestStream(
35 new AsyncCallback(RequsetStreamCallback),
36 request);//异步操作的状态
37 }
38
39 private void RequsetStreamCallback(IAsyncResult result)
40 {
41 HttpWebRequest request = result.AsyncState as HttpWebRequest;
42 request.ContentType = "application/atom+xml";//获取设置HTTP标头值
43 Stream stream = request.EndGetRequestStream(result);//结束对流的异步请求
44 StreamWriter sw = new StreamWriter(stream);
45
46 sw.Write(@" <employee Total='320' compony='BJYD'>
47 <name>keysky</name>
48 <old>24</old>
49 <birthPlace>安徽</birthPlace>
50 <selfinfo>Sports,Programming</selfinfo>
51 </employee>");//写入字符串
52 sw.Close();
53 request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
54 //对internet资源的异步请求
55 }
56 private void ResponseCallback(IAsyncResult result)
57 {
58 HttpWebRequest request = result.AsyncState as HttpWebRequest;
59 WebResponse response = null;
60 try
61 {
62 response = request.EndGetResponse(result);
63 }
64 catch (WebException ex)
65 {
66 StatusString = ex.Status.ToString();
67 }
68
69 synContext.Post(ExtractResponse, response);
70 }
71
72 private void ExtractResponse(object state)
73 {
74 HttpWebResponse response = state as HttpWebResponse;
75
76 if (response != null && response.StatusCode == HttpStatusCode.OK)//响应状态
77 {
78 StreamReader responseReader = new StreamReader(
79 response.GetResponseStream());
80
81 tb1.Text = response.StatusCode.ToString() + "Response: " +
82 responseReader.ReadToEnd();
83 }
84 else
85 {
86 tb1.Text = "Post failed: " + StatusString;
87 }
88 }
89 }
90
91 }
92

运行效果: