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: ...
随机推荐
- 全面理解JavaScript中的闭包的含义及用法
1.什么是闭包 闭包:闭包就是能够读取其他函数内部变量的函数;闭包简单理解成“定义在一个函数内部的函数”. 闭包的形式:即内部函数能够使用它所在级别的外部函数的参数,属性或者内部函数等,并且能在包含它 ...
- [20140117]疑似checkpoint堵塞数据库连接
注:这个说法是不成立的,问题已经解决,但是无法正确的定位到具体什么原因:[20140702]奇怪的应用程序超时 背景: 开发通过应用程序的日志发现间歇性的出现,数据库连接超时 原因: 只能大概猜测,没 ...
- Spring中@Autowired注解、@Resource注解的区别
Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@PostConstruct以及@PreDestroy. @Resour ...
- 编写Java应用程序。首先,定义一个Print类,它有一个方法void output(int x),如果x的值是1,在控制台打印出大写的英文字母表;如果x的值是2,在 控制台打印出小写的英文字母表。其次,再定义一个主类——TestClass,在主类 的main方法中创建Print类的对象,使用这个对象调用方法output ()来打印出大 小写英文字母表。
package zuoye; public class print1 { String a="abcdefghigklmnopqrstuvwxyz"; String B=" ...
- IIS7配置PHP图解(转)
IIS7+PHP_5.2.17 于之前安装IIS的时候已经选上了isapi扩展和isapi筛选,这里就不用另外再添加角色服务了,直接开始 先修改php.ini文件.. 把c:\php下的php.ini ...
- Highcharts使用简例 + 异步动态读取数据
第一部分:在head之间加载两个JS库. <script src="html/js/jquery.js"></script> <script src= ...
- Confluent介绍(二)--confluent platform quickstart
下载 http://www.confluent.io/download,打开后,显示最新版本3.0.0,然后在右边填写信息后,点击Download下载. 之后跳转到下载页面,选择zip 或者 tar都 ...
- Tomcat中取消断点
启动tomcat时,myeclipse报错: This kind of launch is configured to openthe debug perspective when it suspen ...
- CentOS 6.3下配置LVM(逻辑卷管理)
一.简介 LVM是逻辑盘卷管理(Logical Volume Manager)的简称,它是Linux环境下对磁盘分区进行管理的一种机制,LVM是建立在硬盘和分区之上的一个逻辑层,来提高磁盘分区管理的灵 ...
- spring mvc 详细配置(转)
转自: http://www.cnblogs.com/superjt/p/3309255.html 现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是 ...