silverlight: http请求的GET及POST示例

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

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 }
View Code
 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 }
View Code

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>
View Code

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 }
View Code

 

目录
相关文章
|
Android开发 Kotlin
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
1048 2
|
JSON 安全 网络协议
HTTP/HTTPS协议(请求响应模型、状态码)
本文简要介绍了HTTP与HTTPS协议的基础知识。HTTP是一种无状态的超文本传输协议,基于TCP/IP,常用80端口,通过请求-响应模型实现客户端与服务器间的通信;HTTPS为HTTP的安全版本,基于SSL/TLS加密技术,使用443端口,确保数据传输的安全性。文中还详细描述了HTTP请求方法(如GET、POST)、请求与响应头字段、状态码分类及意义,并对比了两者在请求-响应模型中的安全性差异。
1423 20
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
1862 29
|
缓存 安全 API
为什么 HTTP GET 方法不使用请求体?
本指南深入探讨了为什么HTTP GET方法通常不使用请求体,解释了GET方法的主要用途及其设计原则。GET请求旨在通过URL安全、幂等地检索数据,避免因请求体带来的复杂性和潜在问题。尽管HTTP/1.1规范允许GET请求包含请求体,但这并不常见且可能引发副作用。掌握这些原则有助于开发者在API开发中更高效地使用GET请求。
|
API 开发者
了解 HTTP 的PUT 与 POST方法的综合指南
HTTP PUT 和 POST 方法是构建 Web 应用与 API 的核心工具,用于资源的创建与更新。PUT 方法通过指定 URL 更新或创建完整资源,具有幂等性;而 POST 方法更灵活,主要用于创建新资源,但不具备幂等性。本文详细对比了两者在请求体、URL 使用、资源处理等方面的区别,并提供了实际应用示例,帮助开发者根据场景选择合适的方法以优化 API 设计。
1292 13
|
API
掌握 HTTP 请求的艺术:理解 cURL GET 语法
掌握 cURL GET 请求的语法和使用方法是 Web 开发和测试中的基本技能。通过灵活运用 cURL 提供的各种选项,可以高效地与 API 进行交互、调试网络请求,并自动化日常任务。希望本文能帮助读者更好地理解和使用 cURL,提高工作效率和代码质量。
2397 7
|
关系型数据库 MySQL Docker
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
5222 9
|
安全 API 网络安全
使用OkHttp进行HTTPS请求的Kotlin实现
使用OkHttp进行HTTPS请求的Kotlin实现

热门文章

最新文章