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示例的更多相关文章

  1. http异步请求的一种调用示例

    在异步编程中,经常会调用已经写好的异步方法.这时会有一个需求:根据异步方法的返回值,做一些别的操作. 1.0 重新开启一个异步方法,在这个新的异步方法内部,调用需要请求的异步方法.示例: static ...

  2. php发送post请求的三种方法示例

    本文分享下php发送post请求的三种方法与示例代码,分别使用curl.file_get_content.fsocket来实现post提交数据,大家做个参考. php发送post请求的三种方法,分别使 ...

  3. Android 下使用 JSON 实现 HTTP 请求,外加几个示例!

    不得不说,JSON 格式的确是非常美妙的,速度快而且简化了很多操作在 Android 下,Android SDK 已经为我们封装好了整个与 JSON 有关的操作,使用非常方便 以下就是一个标准的 JS ...

  4. asp.net 文件上传示例整理

    ASP.NET依托.net framework类库,封装了大量的功能,使得上传文件非常简单,主要有以下三种基本方法. 方法一:用Web控件FileUpload,上传到网站根目录.  代码如下 复制代码 ...

  5. js原生ajax请求get post笔记

    开拓新领域,贵在记录.下面记录了使用ajax请求的get.post示例代码 //ajax get 请求获取数据支持同步异步 var ajaxGet = function (reqUrl, params ...

  6. 各种编码问题产生原因以及解决办法---------响应编码,请求编码,URL编码

     响应编码 产生原因以及解决办法: 示例: package cn.yzu; import java.io.IOException; import javax.servlet.ServletExcept ...

  7. Nodejs学习笔记(十一)--- 数据采集器示例(request和cheerio)

    目录 写在之前 示例 示例要求 采集器 加入代理 请求https 写在之后... 写在之前 很多人都有做数据采集的需求,用不同的语言,不同的方式都能实现,我以前也用C#写过,主要还是发送各类请求和正则 ...

  8. Silverlight动态设置WCF服务Endpoint

    2013-02-02 05:57 by jv9, 1763 阅读, 3 评论, 收藏, 编辑 去年12月收到一位朋友的邮件,咨询Silverlight使用WCF服务,应用部署后一直无法访问的问题,通过 ...

  9. ASP.NET内置对象之Request传递请求对象

    Request对象是HttpRequest类的一个实例,Request对象用于读取客户端在Web请求期间发送的HTTP值.Request对象常用的属性如下所示. q      QueryString: ...

随机推荐

  1. Eclipse下使用SVN版本控制

    作者:朱先忠编译 转自天极[url]http://dev.yesky.com/356/2578856.shtml[/url] 简单介绍一些基本操作1.同步在Eclipse下,右击你要同步的工程-tea ...

  2. 1、HTML学习 - IT软件人员学习系列文章

    本文做为<IT软件人员学习系列文章>的第一篇,将从最基本的开始进行描述,了解的人完全可以跳过本文(后面会介绍一些工具). 今天讲讲Web开发中最基础的内容:HTML(超文本标记语言).HT ...

  3. 发现IE6的一个BUG,添加受信任站点后,页面无法跳转

    最近客户爆了一个问题,说是最近使用我们的系统,一登录浏览器就直接关闭了.   经排查,属于IE6设置受信任站点的问题,受信任站点设置了通配符,如 http://192.168.1.* 这样的格式,而我 ...

  4. 【hadoop】——HDFS解压缩实现

    转载请注明出处:http://www.cnblogs.com/zhengrunjian/p/4527220.html 所有源码在github上,https://github.com/lastsweet ...

  5. MySQL 中隔离级别 RC 与 RR 的区别

    1. 数据库事务ACID特性 数据库事务的4个特性: 原子性(Atomic): 事务中的多个操作,不可分割,要么都成功,要么都失败: All or Nothing. 一致性(Consistency): ...

  6. 烂泥:linux文件同步之rsync学习(一)

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 这几天刚好有空就打算开始学习linux下的文件同步软件rsync,在学习rsync时,我们可以分以下几个步骤进行: 1. rsync是什么 2. rsy ...

  7. read

    从标准输入读入一行内容并以空格为分隔符赋值给变量,如果输入的内容过多,则把剩下的所有内容都赋值给最后一个变量 $read A B C 123 456 789 101 $echo "$A&qu ...

  8. 利用NuSoap开发WebService(PHP)

    利用NuSoap开发WebService(PHP) 分类: php 2010-09-08 12:00 5005人阅读 评论(1) 收藏 举报 webservicephpsoapstringencodi ...

  9. TCL校园招聘——软件开发工程师(java) 只招5个。。。

    简介 TCL集团股份有限公司创立于1981年,是全球性规模经营的消费类电子企业集团之一,广州2010年亚运会合作伙伴,总部位于广东省惠州市仲恺高新区TCL科技大厦.旗下拥有TCL集团.TCL多媒体科技 ...

  10. Semiautomated IMINT Processing Baseline System——翻译

    题目 半自动的IMINT(图像情报)处理基准系统 摘要 SAIP ACTD(半自动图像情报处理高级概念技术展示项目)的目的是,通过战略上的传感器采集,使图像成为指挥官掌控整个战场的主要源头.该采集系统 ...