介绍
Silverlight 2.0 详解WebRequest和WebResponse,对指定的URI做GET和POST请求,以及接收其响应
HttpWebRequest - 对指定的 URI 发出请求
Create() - 初始化一个 WebRequest
BeginGetResponse() - 开始对指定 URI 资源做异步请求
EndGetResponse() - 结束对指定 URI 资源做异步请求
HttpWebResponse - 对指定的 URI 做出响应
GetResponseStream() - 获取响应的数据流
在线DEMO
http://www.cnblogs.com/webabcd/archive/2008/10/09/1307486.html 示例
1、对指定的URI做GET请求以及接收响应
WebRequestGet.xaml
<UserControl x:Class="Silverlight20.Communication.WebRequestGet"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel HorizontalAlignment="Left" Margin="5">
<TextBlock x:Name="lblMsg" />
</StackPanel>
</UserControl>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
WebRequestGet.xaml.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;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
using System.Threading;
using System.IO;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
namespace Silverlight20.Communication
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public partial class WebRequestGet : UserControl
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// 接收 GET 方式数据的 REST 服务
string _url = "http://localhost:3036/REST.svc/Users/json";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// 异常信息
string _exception = "";
// SynchronizationContext - 同步上下文管理类
SynchronizationContext _syncContext;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public WebRequestGet()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
InitializeComponent();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
Demo();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
void Demo()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// SynchronizationContext.Current - 当前线程的同步上下文
_syncContext = SynchronizationContext.Current;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*
* HttpWebRequest - 对指定的 URI 发出请求
* HttpWebRequest.Create(uri) - 初始化一个 WebRequest
* HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state) - 开始对指定 URI 资源做异步请求
* AsyncCallback callback - System.AsyncCallback 委托。异步操作完成时调用的回调方法
* Object state - 包含此异步请求的对象。即相应的 HttpWebRequest 对象
* HttpWebRequest.Abort() - 取消该异步请求
* HttpWebRequest.Accept - HTTP 头的 Accept 部分
* HttpWebRequest.ContentType - HTTP 头的 ContentType 部分
* HttpWebRequest.Headers - HTTP 头的 key/value 对集合
* HttpWebRequest.Method - HTTP 方法(只支持GET和POST)
* HttpWebRequest.RequestUri - 所请求的 URI
* HttpWebRequest.HaveResponse - 是否接收到了指定 URI 的响应
* HttpWebRequest.AllowReadStreamBuffering - 是否对从 Internet 资源接收的数据做缓冲处理。默认值为true,将数据缓存在客户端内存中,以便随时被应用程序读取
*/
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
HttpWebRequest request = WebRequest.Create(
new Uri(_url, UriKind.Absolute)) as HttpWebRequest;
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
private void ResponseCallback(IAsyncResult result)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// IAsyncResult.AsyncState - AsyncCallback 传过来的对象
HttpWebRequest request = result.AsyncState as HttpWebRequest;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
WebResponse response = null;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
try
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// HttpWebRequest.EndGetResponse(IAsyncResult) - 结束对指定 URI 资源做异步请求
// 返回值为 WebResponse 对象
response = request.EndGetResponse(result) as HttpWebResponse;
}
catch (Exception ex)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
_exception = ex.ToString();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// SynchronizationContext.Post(SendOrPostCallback d, Object state) - 将异步消息发送到该同步上下文中
// SendOrPostCallback d - System.Threading.SendOrPostCallback 委托
// Object state - 需要传递的参数
_syncContext.Post(GetResponse, response);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
private void GetResponse(object state)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*
* HttpWebResponse - 对指定的 URI 做出响应
* GetResponseStream() - 获取响应的数据流
*/
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
HttpWebResponse response = state as HttpWebResponse;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
if (response != null)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Stream responseStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(responseStream))
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
lblMsg.Text = sr.ReadToEnd();
}
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
lblMsg.Text = _exception;
}
}
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2、对指定的URI做POST请求以及接收响应
WebRequestPost.xaml
<UserControl x:Class="Silverlight20.Communication.WebRequestPost"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel HorizontalAlignment="Left" Margin="5">
<TextBlock x:Name="lblMsg" />
</StackPanel>
</UserControl>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
WebRequestPost.xaml.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;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
using System.Threading;
using System.IO;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
namespace Silverlight20.Communication
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public partial class WebRequestPost : UserControl
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// 接收 POST 方式数据的 REST 服务
string _url = "http://localhost:3036/REST.svc/PostUser";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// 异常信息
string _exception = "";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// SynchronizationContext - 同步上下文管理类
SynchronizationContext _syncContext;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public WebRequestPost()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
InitializeComponent();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
Demo();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
void Demo()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
_syncContext = SynchronizationContext.Current;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
HttpWebRequest request = WebRequest.Create(
new Uri(_url, UriKind.Absolute)) as HttpWebRequest;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
request.Method = "POST";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// BeginGetRequestStream(AsyncCallback callback, Object state) - 向指定的 URI 资源发送数据的流的异步请求
// AsyncCallback callback - System.AsyncCallback 委托
// Object state - 包含此异步请求的对象。即相应的 HttpWebRequest 对象
IAsyncResult asyncResult = request.BeginGetRequestStream(
new AsyncCallback(RequestStreamCallback), request);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
private void RequestStreamCallback(IAsyncResult result)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
request.ContentType = "application/x-www-form-urlencoded";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// HttpWebRequest.EndGetRequestStream(IAsyncResult) - 返回用于将数据写入某 URI 资源的 Stream
Stream requestStream = request.EndGetRequestStream(result);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
StreamWriter streamWriter = new StreamWriter(requestStream);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// byte[] postdata = System.Text.Encoding.UTF8.GetBytes("name=webabcd");
// 多个参数用“&”分隔
streamWriter.Write("name=webabcd");
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
streamWriter.Close();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
private void ResponseCallback(IAsyncResult result)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
WebResponse response = null;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
try
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
response = request.EndGetResponse(result);
}
catch (Exception ex)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
_exception = ex.ToString();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// 调用 UI 线程
_syncContext.Post(GetResponse, response);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
private void GetResponse(object state)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*
* HttpWebResponse - 对指定的 URI 做出响应
* GetResponseStream() - 获取响应的数据流
* ContentLength - 接收的数据的内容长度
* ContentType - HTTP 头的 ContentType 部分
* Method - HTTP 方法
* ResponseUri - 响应该请求的 URI
* StatusCode - 响应状态 [System.Net.HttpStatusCode枚举]
* HttpStatusCode.OK - HTTP 状态为 200
* HttpStatusCode.NotFound - HTTP 状态为 404
* StatusDescription - 响应状态的说明
*/
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
HttpWebResponse response = state as HttpWebResponse;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
if (response != null && response.StatusCode == HttpStatusCode.OK)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Stream responseStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(responseStream))
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
lblMsg.Text = string.Format("接收的数据的内容长度:{0}\r\nHTTP 头的 ContentType 部分:{1}\r\nHTTP 方法:{2}\r\n响应该请求的 URI:{3}\r\n响应状态:{4}\r\n响应状态的说明:{5}\r\n响应的结果:{6}\r\n",
response.ContentLength,
response.ContentType,
response.Method,
response.ResponseUri,
response.StatusCode,
response.StatusDescription,
sr.ReadToEnd());
}
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
lblMsg.Text = _exception;
}
}
}
}