silverlight: http请求的GET及POST示例

http请求的get/post并不是难事,只是silverlight中一切皆是异步,所以代码看起来就显得有些冗长了,下面这个HttpHelper是在总结 园友 的基础上,修改得来:

 1 namespace SLAwb.Helper
 2 {
 3     public sealed class MediaType
 4     {
 5         /// <summary>
 6         /// "application/xml"
 7         /// </summary>
 8         public const string APPLICATION_XML = "application/xml";
 9 
10         /// <summary>
11         /// application/json
12         /// </summary>
13         public const string APPLICATION_JSON = "application/json";
14 
15         /// <summary>
16         /// "application/x-www-form-urlencoded"
17         /// </summary>
18         public const string APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded";
19      
20     }
21 }
 1 using System;
 2 using System.IO;
 3 using System.Net;
 4 using System.Threading;
 5 
 6 namespace SLAwb.Helper
 7 {
 8     /// <summary>
 9     /// Http工具类,用于向指定url发起Get或Post请求
10     /// http://yjmyzz.cnblogs.com/
11     /// </summary>
12     public class HttpHelper
13     {
14         private string postData;
15         SynchronizationContext currentContext;
16         SendOrPostCallback sendOrPostCallback;
17 
18         /// <summary>
19         /// 从指定url以Get方式获取数据
20         /// </summary>
21         /// <param name="url"></param>
22         /// <param name="completedHandler"></param>
23         public void Get(string url, DownloadStringCompletedEventHandler completedHandler)
24         {
25             WebClient client = new WebClient();
26             client.DownloadStringCompleted += completedHandler;
27             client.DownloadStringAsync(new Uri(url));
28         }
29 
30 
31 
32         /// <summary>
33         /// 向指定url地址Post数据
34         /// </summary>
35         /// <param name="url"></param>
36         /// <param name="data"></param>
37         /// <param name="mediaType"></param>
38         /// <param name="synchronizationContext"></param>
39         /// <param name="callBack"></param>
40         public void Post(string url, string data, string mediaType, SynchronizationContext synchronizationContext, SendOrPostCallback callBack)
41         {
42             currentContext = synchronizationContext;
43             Uri endpoint = new Uri(url);
44             sendOrPostCallback = callBack;
45             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
46             request.Method = "POST";
47             request.ContentType = mediaType;
48             postData = data;
49             request.BeginGetRequestStream(new AsyncCallback(RequestReadySocket), request);
50         }
51 
52         private void RequestReadySocket(IAsyncResult asyncResult)
53         {
54             WebRequest request = asyncResult.AsyncState as WebRequest;
55             Stream requestStream = request.EndGetRequestStream(asyncResult);
56 
57             using (StreamWriter writer = new StreamWriter(requestStream))
58             {
59                 writer.Write(postData);
60                 writer.Flush();
61             }
62 
63             request.BeginGetResponse(new AsyncCallback(ResponseReadySocket), request);
64         }
65 
66         private void ResponseReadySocket(IAsyncResult asyncResult)
67         {
68             try
69             {
70                 WebRequest request = asyncResult.AsyncState as WebRequest;
71                 WebResponse response = request.EndGetResponse(asyncResult);
72                 using (Stream responseStream = response.GetResponseStream())
73                 {
74                     StreamReader reader = new StreamReader(responseStream);
75                     string paramStr = reader.ReadToEnd();
76                     currentContext.Post(sendOrPostCallback, paramStr);
77                 }
78             }
79             catch (Exception e)
80             {
81                 currentContext.Post(sendOrPostCallback, e.Message); 
82             }
83             
84         }
85 
86 
87     }
88 }

Silverlight中的测试代码: xaml部分

 1 <UserControl x:Class="SLAwb.MainPage"
 2     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6     mc:Ignorable="d"
 7     d:DesignHeight="480" d:DesignWidth="640">
 8 
 9     <Grid x:Name="LayoutRoot" Background="White">
10         <Grid.RowDefinitions>
11             <RowDefinition Height="30"></RowDefinition>
12             <RowDefinition Height="*"></RowDefinition>
13             <RowDefinition Height="2*"></RowDefinition>
14         </Grid.RowDefinitions>        
15         <Grid Grid.Row="0" Margin="3">
16             <Grid.ColumnDefinitions>
17                 <ColumnDefinition Width="40"></ColumnDefinition>
18                 <ColumnDefinition Width="*"></ColumnDefinition>
19                 <ColumnDefinition Width="75"></ColumnDefinition>
20                 <ColumnDefinition Width="95"></ColumnDefinition>
21                 <ColumnDefinition Width="80"></ColumnDefinition>
22                 <ColumnDefinition Width="80"></ColumnDefinition>
23             </Grid.ColumnDefinitions>
24             <TextBlock VerticalAlignment="Center" TextAlignment="Right">地址:</TextBlock>
25             <TextBox Name="txtUrl" Grid.Column="1" Text="http://localhost/"></TextBox>
26             <TextBlock Grid.Column="2" VerticalAlignment="Center" TextAlignment="Right">MediaType:</TextBlock>
27             <TextBox Name="txtMediaType" Grid.Column="3" Text="application/xml"></TextBox>
28             <Button Name="btnPost" Content="Post" Grid.Column="4" Margin="3,1" Click="btnPost_Click"></Button>
29             <Button Name="btnGet" Content="Get" Grid.Column="5" Margin="3,1" Click="btnGet_Click"></Button>
30         </Grid>
31         
32         <Grid Grid.Row="1">
33             <Grid.ColumnDefinitions>
34                 <ColumnDefinition Width="40"></ColumnDefinition>
35                 <ColumnDefinition Width="*"></ColumnDefinition>
36             </Grid.ColumnDefinitions>
37             <TextBlock VerticalAlignment="Top" TextAlignment="Right">数据:</TextBlock>
38             <TextBox Name="txtPostData" Grid.Column="1" Margin="3" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></TextBox>
39         </Grid>
40 
41         <Grid Grid.Row="2">
42             <Grid.ColumnDefinitions>
43                 <ColumnDefinition Width="40"></ColumnDefinition>
44                 <ColumnDefinition Width="*"></ColumnDefinition>
45             </Grid.ColumnDefinitions>
46             <TextBlock VerticalAlignment="Top" TextAlignment="Right">返回:</TextBlock>
47             <TextBox Name="txtResult" Grid.Column="1" Margin="3" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></TextBox>
48         </Grid>
49     </Grid>
50 </UserControl>

cs部分

 1 using SLAwb.Helper;
 2 using System;
 3 using System.Net;
 4 using System.Threading;
 5 using System.Windows;
 6 using System.Windows.Controls;
 7 
 8 namespace SLAwb
 9 {
10     public partial class MainPage : UserControl
11     {
12         private SynchronizationContext currentContext;
13 
14 
15         public MainPage()
16         {
17             InitializeComponent();
18             this.currentContext = SynchronizationContext.Current;
19         }
20 
21         private void btnPost_Click(object sender, RoutedEventArgs e)
22         {
23             BeforeReturn();
24             HttpHelper httpHelper = new HttpHelper();
25             httpHelper.Post(txtUrl.Text, txtPostData.Text, txtMediaType.Text, currentContext, PostCompletedHandler);
26         }
27 
28         private void PostCompletedHandler(Object obj)
29         {
30             txtResult.Text = obj.ToString();
31         }
32 
33         private void btnGet_Click(object sender, RoutedEventArgs e)
34         {
35             BeforeReturn();
36             HttpHelper httpHelper = new HttpHelper();
37             httpHelper.Get(txtUrl.Text, GetCompletedHandler);            
38         }
39 
40 
41         void BeforeReturn() {
42             txtResult.Text = "loading...";
43         }
44 
45 
46         void GetCompletedHandler(object sender, DownloadStringCompletedEventArgs e)
47         {
48             if (e.Error == null)
49             {
50                 txtResult.Text = e.Result;
51             }
52             else
53             {
54                 txtResult.Text = e.Error.Message;
55             }
56         }
57     }
58 }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏ASP.NET MVC5 后台权限管理系统

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(13)-系统日志和异常的处理③

上一节我们讲了如何捕获异常和记录日志,这一节我们讲,没有捕获的或者忘记捕获的异常包括404错误等,我们统一处理这个异常。 这一讲是利用 Application_...

31280
来自专栏飞扬的花生

将Json数据保存在静态脚本文件中读取

      一些常用的数据例如一些网站的区域信息被改变的可能性不大,一般不通过请求获取,于是我们选择存在静态文件中,例如以下Demo: 1.动态加载Json数据...

31260
来自专栏.NET开发那点事

.NET开源高性能Socket通信中间件Helios介绍及演示

  Helios是一套高性能的Socket通信中间件,使用C#编写。Helios的开发受到Netty的启发,使用非阻塞的事件驱动模型架构来实现高并发高吞吐量。H...

25620
来自专栏飞扬的花生

C#实现Excel模板导出和从Excel导入数据

      午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 ? 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.O...

69270
来自专栏张高兴的博客

张高兴的 Windows 10 IoT 开发笔记:串口红外编解码模块 YS-IRTM

This is a Windows 10 IoT Core project on the Raspberry Pi 2/3, coded by C#.

20920
来自专栏林德熙的博客

win10 uwp 读取保存WriteableBitmap 、BitmapImage 保存 WriteableBitmap 到文件从文件读 WriteableBitmapIma

我们在UWP,经常使用的图片,数据结构就是 BitmapImage 和 WriteableBitmap。关于 BitmapImage 和 WriteableBi...

15310
来自专栏c#开发者

MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具集成Visual Studio 2013

MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具 经过一个多星期的努力总算完成了单表,多...

473130
来自专栏菩提树下的杨过

ExtJs学习笔记(5)_Ajax示例

ExtJs对于Ajax的使用非常简单,看下面的代码: 1.Html页: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0...

22860
来自专栏hbbliyong

C# ini文件读写类

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类, 从网上收集的,很全,就是没有对...

35760
来自专栏函数式编程语言及工具

Akka(29): Http:Server-Side-Api,Low-Level-Api

 Akka-http针对Connection的两头都提供了方便编程的Api,分别是Server-Side-Api和Client-Side-Api。通过这两个Ap...

22480

扫码关注云+社区

领取腾讯云代金券