Silverlight 2.0 正式版跨域提交数据全攻略

【注】本文代码基于 Silverlight 2.0 正式版。

Silverlight 2.0 正式版发布之后,在 HttpWebrequest 方面也发生了一些变化,以前的代码正式版里面可能就无法运行了,具体的

变化主要有:
1,在调用 HttpWebRequest.BeginGetResponse() 之前,Request 流必须关闭;
2,HttpWebRequest.EndGetResponse() 抛出的异常,正式版之前,HttpWebRequest.BeingGetResponse() 中跨域、跨协议访问抛出安全性异常,其他的请求都返回404错误,现在,HttpRequest.EndGetResponse()的错误将作为异常抛出,涉及安全问题的错误抛出 SecurityException,非成功的请求会抛出 WebException 异常,WebException.Response 被设置成 HttpStatusCode.NotFound。

由于 HttpWebrequest 发送的是异步请求,如果要与界面交互,还涉及到线程同步的问题,如果不进行线程同步,会报告“跨线程访问无效”的错误。下面就以实际的例子来向一个 Java Servlet 地址提交数据,将提交的数据返回到当前界面中。当然,提交到 aspx 页面上也没有问题的,只需要在 Page_Load 事件处理方法里加入下面的代码即可:

protected void Page_Load(object sender, EventArgs e)
{
if (Request.RequestType.Equals("POST"))
{
Response.ClearContent();
Response.ClearHeaders();
Response.Write("您提交的数据是:" + Request.Params.Get("data"));
Response.End();
return;
}
}

如果提交到 Java Servlet,则测试代码可以写:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().print("您提交的数据是:" + request.getParameter("data"));
}


要在本机进行跨域测试,需要在hosts文件进行设置,如:

127.0.0.1www.mengxianhui.com
127.0.0.1www.xianhuimeng.com

这样,就可以在你自己的机器上进行跨域测试了,不过,需要记住,默认情况下,Silverlight 是不允许跨域访问的,因此,需要在接收数据的网站根目录下(记住是网站根目录,不是应用程序的根目录)放置一个策略文件,clientaccesspolicy.xml 或者 crossdomain.xml :


clientaccesspolicy.xml 内容设置如下:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*" />
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

crossdomain.xml 内容设置如下:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

本例子中使用的 Page.xaml 如下:

<UserControl xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
x:Class="SilverlightApplication3.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Width="400" Height="300" Canvas.Left="2">
<TextBox x:Name="data" Canvas.Left="2" Canvas.Top="2" Height="30" Width="180" Text="【孟子E章】测试数据" FontSize="16"></TextBox>
<Button Content="发送POST数据" Width="100" Height="30" Click="PostData" Canvas.Top="2" Canvas.Left="200"></Button>
<TextBlock x:Name="result" Canvas.Top="40" FontSize="16"></TextBlock>
</Canvas>
</Grid>
</UserControl>

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


namespace SilverlightApplication3
{
public partial class Page : UserControl
{

public Page()
{
InitializeComponent();

//设置当前界面线程
syncContext = SynchronizationContext.Current;
}

private SynchronizationContext syncContext;
private String postData = String.Empty;

private void PostData(object sender, RoutedEventArgs e)
{
//请注意:Silverlight 里的 HttpWebRequest, Encoding 类的属性和方法与常规的 .NET Framework 里面还是不同的。
result.Text = "开始提交数据……";
postData = "data=" + data.Text; //要提交的内容
Uri url = new Uri("http://www.mengxianhui.com/admin?tmp=" + DateTime.Now.Ticks.ToString(), UriKind.Absolute);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(url);
request.Method = "POST"; // Silverlight 只支持 GET 和 POST 方法
request.AllowReadStreamBuffering = true;
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
}

private void RequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
StreamWriter postStream = new StreamWriter(request.EndGetRequestStream(asyncResult));
//byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//Encoding.GetEncoding()方法只支持四种编码。utf-8 , utf-16 , utf-16BE , utf-16LE
postStream.Write(postData); //处理中文的问题。不要使用 Stream 的 Write 方法。
postStream.Close();
postStream.Dispose();
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
}

void ResponseReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
WebResponse response = request.EndGetResponse(asyncResult) as WebResponse;

//同步线程上下文
if (syncContext == null) syncContext = new SynchronizationContext();
syncContext.Post(ExtractResponse, response);
}

private void ExtractResponse(object state)
{
WebResponse response = state as WebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader streamRead = new StreamReader(responseStream);
//显示返回的数据
result.Text = new StreamReader(responseStream).ReadToEnd();
response.Close();
responseStream.Close();
responseStream.Dispose();
streamRead.Close();
streamRead.Dispose();
}
}
}

测试结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值