您的位置:首页 > 理论基础 > 计算机网络

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

2010-03-08 11:49 639 查看

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:

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 System.Xml;
using System.IO;
using System.Text;
using System.IO.IsolatedStorage;

namespace XMLWriter_XmlReader
{
public partial class MainPage : UserControl
{
string strxml = string.Empty;
public MainPage()
{
InitializeComponent();
CreateXML();
ReadXML();
OperateIsolatedStorageFile();
}
private void CreateXML()
{
strxml = @" <employee Total='320' compony='BJYD'>
<name>keysky</name>
<old>24</old>
<birthPlace>安徽</birthPlace>
<selfinfo>Sports,Programming</selfinfo>
</employee>";
}
private void ReadXML()
{
StringBuilder xml = new StringBuilder();
using (XmlReader xmlread = XmlReader.Create(new StringReader(strxml)))
{
xmlread.ReadToFollowing("employee");//找到需要获取的元素节点
xmlread.MoveToAttribute(1);//读取索引第一个属性
xml.AppendLine("公司名称:" + xmlread.Value);
xmlread.ReadToFollowing("name");
xml.AppendLine("name:" + xmlread.ReadElementContentAsString());
xmlread.ReadToFollowing("selfinfo");
xml.AppendLine("selfinfo:" + xmlread.ReadElementContentAsString());
}
tb1.Text = xml.ToString();
}
private void OperateIsolatedStorageFile()
{
using (IsolatedStorageFile StorageFile = IsolatedStorageFile.
GetUserStoreForApplication())
//获取主机独立存储区
{
using (IsolatedStorageFileStream StorageStream = new
IsolatedStorageFileStream("Storage.xml",
FileMode.Create, StorageFile))
//创建并初始化独立存储流
{
XmlWriterSettings settings = new XmlWriterSettings();//初始化xmlwriter
settings.Indent = true;//元素自动缩进
using (XmlWriter writer = XmlWriter.Create(StorageStream, settings))
{
writer.WriteComment("Storage XML Document");//写入xml文本注释
writer.WriteStartElement("Employee");//写入开始标记
writer.WriteAttributeString("Compony", "BJYD");//写入标记属性
writer.WriteAttributeString("Total", "320");
writer.WriteStartElement("name");//写入开始元素标记
writer.WriteString("keysky");//写入元素字符串
writer.WriteEndElement();//关闭元素命名空间

writer.WriteStartElement("selfinfo");
writer.WriteString("Sports,Programming");
writer.WriteEndElement();

writer.Flush();//刷新数据流
}
}

using (StreamReader sr = new StreamReader(StorageFile.OpenFile
("Storage.xml", FileMode.Open)))
{
tb2.Text = sr.ReadToEnd();
}
StorageFile.DeleteFile("Storage.xml");//删除独立存储区的文件
}
}

}
}

运行效果:



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:

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;

namespace CommunicationOfWebclient
{
public partial class MainPage : UserControl
{
WebClient client = new WebClient();
public MainPage()
{
InitializeComponent();
client.UploadStringCompleted += new
UploadStringCompletedEventHandler(uploadStrCompleted);
client.UploadProgressChanged += new
UploadProgressChangedEventHandler(uploadProgress);
client.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(downloadStrCompleted);
client.DownloadProgressChanged += new
DownloadProgressChangedEventHandler(downloadProgress);
}
private void uploadStrCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null) MessageBox.Show(e.Error.Message);
else tb1.Text = e.Result;//获取服务器回复
}

private void uploadProgress(object sender, UploadProgressChangedEventArgs e)
{
tb2.Text = "上传完成百分比:" + e.ProgressPercentage.ToString()
+ " 上传字节数:" + e.BytesSent.ToString();
//获取下载百分比和字节数
}

private void btn1_Click(object sender, RoutedEventArgs e)
{
string strpost = @" <employee Total='320' compony='BJYD'>
<name>keysky</name>
<old>24</old>
<birthPlace>安徽</birthPlace>
<selfinfo>Sports,Programming</selfinfo>
</employee>";
client.UploadStringAsync(new Uri("http://localhost/engin/info.asp",
UriKind.Absolute), strpost);
}

private void btn2_Click(object sender, RoutedEventArgs e)
{
client.DownloadStringAsync(new Uri("http://localhost/engin/info.asp",
UriKind.Absolute));
}

private void downloadStrCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null) MessageBox.Show(e.Error.Message);
else tb3.Text = e.Result;
}

private void downloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
tb4.Text = "下载完成百分比:" + e.ProgressPercentage.ToString()
+ " 下载字节数:" + e.BytesReceived.ToString();
}
}
}

运行效果:



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:

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 System.Threading;
using System.IO;

namespace CommunicationOfWebRequestWebResponse
{
public partial class MainPage : UserControl
{
SynchronizationContext synContext;
string StatusString;
public MainPage()
{
InitializeComponent();
}

private void btnPost_Click(object sender, RoutedEventArgs e)
{
synContext = SynchronizationContext.Current;//获取当前线程上下文

HttpWebRequest request = WebRequest.Create(new Uri("http://localhost/engin/info.asp",
UriKind.Absolute)) as HttpWebRequest;
request.Method = "POST";//设置请求方法为POST

IAsyncResult asynResult = request.BeginGetRequestStream(
new AsyncCallback(RequsetStreamCallback),
request);//异步操作的状态
}

private void RequsetStreamCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
request.ContentType = "application/atom+xml";//获取设置HTTP标头值
Stream stream = request.EndGetRequestStream(result);//结束对流的异步请求
StreamWriter sw = new StreamWriter(stream);

sw.Write(@" <employee Total='320' compony='BJYD'>
<name>keysky</name>
<old>24</old>
<birthPlace>安徽</birthPlace>
<selfinfo>Sports,Programming</selfinfo>
</employee>");//写入字符串
sw.Close();
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
//对internet资源的异步请求
}
private void ResponseCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
WebResponse response = null;
try
{
response = request.EndGetResponse(result);
}
catch (WebException ex)
{
StatusString = ex.Status.ToString();
}

synContext.Post(ExtractResponse, response);
}

private void ExtractResponse(object state)
{
HttpWebResponse response = state as HttpWebResponse;

if (response != null && response.StatusCode == HttpStatusCode.OK)//响应状态
{
StreamReader responseReader = new StreamReader(
response.GetResponseStream());

tb1.Text = response.StatusCode.ToString() + "Response: " +
responseReader.ReadToEnd();
}
else
{
tb1.Text = "Post failed: " + StatusString;
}
}
}

}

运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐