silverlight: http请求的GET及POST示例
http请求的get/post并不是难事,只是silverlight中一切皆是异步,所以代码看起来就显得有些冗长了,下面这个HttpHelper是在总结 园友 的基础上,修改得来:
namespace SLAwb.Helper
{
public sealed class MediaType
{
/// <summary>
/// "application/xml"
/// </summary>
public const string APPLICATION_XML = "application/xml"; /// <summary>
/// application/json
/// </summary>
public const string APPLICATION_JSON = "application/json"; /// <summary>
/// "application/x-www-form-urlencoded"
/// </summary>
public const string APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded"; }
}
using System;
using System.IO;
using System.Net;
using System.Threading; namespace SLAwb.Helper
{
/// <summary>
/// Http工具类,用于向指定url发起Get或Post请求
/// http://yjmyzz.cnblogs.com/
/// </summary>
public class HttpHelper
{
private string postData;
SynchronizationContext currentContext;
SendOrPostCallback sendOrPostCallback; /// <summary>
/// 从指定url以Get方式获取数据
/// </summary>
/// <param name="url"></param>
/// <param name="completedHandler"></param>
public void Get(string url, DownloadStringCompletedEventHandler completedHandler)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += completedHandler;
client.DownloadStringAsync(new Uri(url));
} /// <summary>
/// 向指定url地址Post数据
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="mediaType"></param>
/// <param name="synchronizationContext"></param>
/// <param name="callBack"></param>
public void Post(string url, string data, string mediaType, SynchronizationContext synchronizationContext, SendOrPostCallback callBack)
{
currentContext = synchronizationContext;
Uri endpoint = new Uri(url);
sendOrPostCallback = callBack;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.ContentType = mediaType;
postData = data;
request.BeginGetRequestStream(new AsyncCallback(RequestReadySocket), request);
} private void RequestReadySocket(IAsyncResult asyncResult)
{
WebRequest request = asyncResult.AsyncState as WebRequest;
Stream requestStream = request.EndGetRequestStream(asyncResult); using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(postData);
writer.Flush();
} request.BeginGetResponse(new AsyncCallback(ResponseReadySocket), request);
} private void ResponseReadySocket(IAsyncResult asyncResult)
{
try
{
WebRequest request = asyncResult.AsyncState as WebRequest;
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
string paramStr = reader.ReadToEnd();
currentContext.Post(sendOrPostCallback, paramStr);
}
}
catch (Exception e)
{
currentContext.Post(sendOrPostCallback, e.Message);
} } }
}
Silverlight中的测试代码:
xaml部分
<UserControl x:Class="SLAwb.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="480" d:DesignWidth="640"> <Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="75"></ColumnDefinition>
<ColumnDefinition Width="95"></ColumnDefinition>
<ColumnDefinition Width="80"></ColumnDefinition>
<ColumnDefinition Width="80"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" TextAlignment="Right">地址:</TextBlock>
<TextBox Name="txtUrl" Grid.Column="1" Text="http://localhost/"></TextBox>
<TextBlock Grid.Column="2" VerticalAlignment="Center" TextAlignment="Right">MediaType:</TextBlock>
<TextBox Name="txtMediaType" Grid.Column="3" Text="application/xml"></TextBox>
<Button Name="btnPost" Content="Post" Grid.Column="4" Margin="3,1" Click="btnPost_Click"></Button>
<Button Name="btnGet" Content="Get" Grid.Column="5" Margin="3,1" Click="btnGet_Click"></Button>
</Grid> <Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Top" TextAlignment="Right">数据:</TextBlock>
<TextBox Name="txtPostData" Grid.Column="1" Margin="3" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></TextBox>
</Grid> <Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Top" TextAlignment="Right">返回:</TextBlock>
<TextBox Name="txtResult" Grid.Column="1" Margin="3" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></TextBox>
</Grid>
</Grid>
</UserControl>
cs部分
using SLAwb.Helper;
using System;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls; namespace SLAwb
{
public partial class MainPage : UserControl
{
private SynchronizationContext currentContext; public MainPage()
{
InitializeComponent();
this.currentContext = SynchronizationContext.Current;
} private void btnPost_Click(object sender, RoutedEventArgs e)
{
BeforeReturn();
HttpHelper httpHelper = new HttpHelper();
httpHelper.Post(txtUrl.Text, txtPostData.Text, txtMediaType.Text, currentContext, PostCompletedHandler);
} private void PostCompletedHandler(Object obj)
{
txtResult.Text = obj.ToString();
} private void btnGet_Click(object sender, RoutedEventArgs e)
{
BeforeReturn();
HttpHelper httpHelper = new HttpHelper();
httpHelper.Get(txtUrl.Text, GetCompletedHandler);
} void BeforeReturn() {
txtResult.Text = "loading...";
} void GetCompletedHandler(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
txtResult.Text = e.Result;
}
else
{
txtResult.Text = e.Error.Message;
}
}
}
}

silverlight: http请求的GET及POST示例的更多相关文章
- http异步请求的一种调用示例
在异步编程中,经常会调用已经写好的异步方法.这时会有一个需求:根据异步方法的返回值,做一些别的操作. 1.0 重新开启一个异步方法,在这个新的异步方法内部,调用需要请求的异步方法.示例: static ...
- php发送post请求的三种方法示例
本文分享下php发送post请求的三种方法与示例代码,分别使用curl.file_get_content.fsocket来实现post提交数据,大家做个参考. php发送post请求的三种方法,分别使 ...
- Android 下使用 JSON 实现 HTTP 请求,外加几个示例!
不得不说,JSON 格式的确是非常美妙的,速度快而且简化了很多操作在 Android 下,Android SDK 已经为我们封装好了整个与 JSON 有关的操作,使用非常方便 以下就是一个标准的 JS ...
- asp.net 文件上传示例整理
ASP.NET依托.net framework类库,封装了大量的功能,使得上传文件非常简单,主要有以下三种基本方法. 方法一:用Web控件FileUpload,上传到网站根目录. 代码如下 复制代码 ...
- js原生ajax请求get post笔记
开拓新领域,贵在记录.下面记录了使用ajax请求的get.post示例代码 //ajax get 请求获取数据支持同步异步 var ajaxGet = function (reqUrl, params ...
- 各种编码问题产生原因以及解决办法---------响应编码,请求编码,URL编码
响应编码 产生原因以及解决办法: 示例: package cn.yzu; import java.io.IOException; import javax.servlet.ServletExcept ...
- Nodejs学习笔记(十一)--- 数据采集器示例(request和cheerio)
目录 写在之前 示例 示例要求 采集器 加入代理 请求https 写在之后... 写在之前 很多人都有做数据采集的需求,用不同的语言,不同的方式都能实现,我以前也用C#写过,主要还是发送各类请求和正则 ...
- Silverlight动态设置WCF服务Endpoint
2013-02-02 05:57 by jv9, 1763 阅读, 3 评论, 收藏, 编辑 去年12月收到一位朋友的邮件,咨询Silverlight使用WCF服务,应用部署后一直无法访问的问题,通过 ...
- ASP.NET内置对象之Request传递请求对象
Request对象是HttpRequest类的一个实例,Request对象用于读取客户端在Web请求期间发送的HTTP值.Request对象常用的属性如下所示. q QueryString: ...
随机推荐
- JQuery插件:遮罩+数据加载中。。。(特点:遮你想遮,罩你想罩)
在很多项目中都会涉及到数据加载.数据加载有时可能会是2-3秒,为了给一个友好的提示,一般都会给一个[数据加载中...]的提示.今天就做了一个这样的提示框. 先去jQuery官网看看怎么写jQuery插 ...
- InnoDB源码分析--事务日志(二)
原创文章,转载请标明原文链接:http://www.cnblogs.com/wingsless/p/5708992.html 昨天写了有关事务日志的一些基本点(http://www.cnblogs.c ...
- 描述Linux系统开机到登陆界面的启动过程(计时2分钟)
简述: 1.开机BIOS自检 2.MBR引导 3.grub引导菜单 4.加载内核kernel 5.启动init进程 6.读取inittab文件,执行rc.sysinit,rc等脚本 7.启动minge ...
- 工作中常用的Linux命令:find命令
本文链接:http://www.cnblogs.com/MartinChentf/p/6056571.html (转载请注明出处) 1.命令格式 find [-H] [-L] [-P] [-D deb ...
- 根据网站所做的SEO优化整理的一份文档
今日给合作公司讲解本公司网站SEO优化整理的一份简单文档 架构 ########################################## 1.尽量避免Javascript和flash导航. ...
- scala 第一课
val msg="Hello,World" Scala 可以根据赋值的内容推算出变量的类型.这在Scala语言中成为"type inference". Scal ...
- Windows Azure Redis 缓存服务
8月20日,Windows Azure (中国版)开始提供Redis缓存服务,比较国际版的Microsoft Azure晚了差不多一年的时间.说实话,微软真不应该将这个重要的功能delay这么长时间, ...
- Java实现点击一个控件实现删除一个控件的方法
最近在做项目的时候需要处理点击一个JLabel实现删除这一个JLabel的功能.最近折磨了一点时间,查了一下API.找到2个方法可以实现这个功能. remove public void remove( ...
- 怎样在ZBrush中快速绘制人体躯干
之前我们对人体骨点的雕刻,了解了人体骨骼比例结构特征.今天的ZBrush教程将通过ZBrush®遮罩显示的特点对模型的人体躯干进行细致雕刻.文章内容仅以fisker老师讲述为例,您也可以按照自己的想法 ...
- 当手机被PS掉,人们看到的是手中的灵魂
Eric Pickersgill是一名摄影师,最近喜欢拍摄并记录人们使用智能手机的情景,不过不同的是,在最终作品中会将手机从人们手中PS掉,一刹那会进入一个奇怪的世界.黑白照片也极具冲击力. 每个人神 ...