silverlight: http请求的GET及POST示例

2018-01-19 11:06:24 浏览数 (1)

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

代码语言:javascript复制
 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 }
代码语言:javascript复制
 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部分

代码语言:javascript复制
 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部分

代码语言:javascript复制
 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 人点赞