【注】本文代码基于 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.1 www.mengxianhui.com
127.0.0.1 www.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();
}
}
}
测试结果:
总结以上是内存溢出为你收集整理的Silverlight 2.0 正式版跨域提交数据全攻略全部内容,希望文章能够帮你解决Silverlight 2.0 正式版跨域提交数据全攻略所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)