silverlight: http请求的GET及POST示例

时间:2024-10-19 22:06:20

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示例