Windows Phone 平台上的 Post 到服务器时的数据传输

原作者的Code链接:http://postclient.codeplex.com/

类:DownloadStringCompletedEventArgs:EventArgs ,为DownloadStringCompleted事件提供数据:下载下来的数据资源,执行异步操作时引发的异常

 1     /// <summary>
 2     /// 为DownloadStringCompleted事件提供数据
 3     /// </summary>
 4     public class DownloadStringCompletedEventArgs:EventArgs
 5     {
 6         #region 属性
 7 
 8         /// <summary>
 9         /// 通过DownloadStringAsynchronous方法下载的数据
10         /// </summary>
11         public string Result { get; private set; }
12 
13         /// <summary>
14         /// 执行异步操作时引发的异常
15         /// </summary>
16         public Exception Error { get; private set; }
17 
18         #endregion
19 
20         #region 构造方法
21 
22         /// <summary>
23         /// 创建一个含有指定返回数据的实例
24         /// </summary>
25         /// <param name="result">通过DownloadStringAsynchronous方法下载的数据</param>
26         public DownloadStringCompletedEventArgs(string result)
27         {
28             Result=result;
29         }
30 
31         /// <summary>
32         /// 创建一个含有指定异常的实例
33         /// </summary>
34         /// <param name="ex">执行异步操作时引发的异常</param>
35         public DownloadStringCompletedEventArgs(Exception ex)
36         {
37             Error = ex;
38         }
39         #endregion
40     }

类:PostClient ,主要实现方法,PostClient(),3重载; DownloadStringAsync(Uri address) ,实现资源加载

  1     /// <summary>
  2     /// 包含将数据传送到HTTP Post 网络请求 和 从 HTTP Post 网络请求接收数据的常用方法
  3     /// </summary>
  4     public class PostClient
  5     {
  6 
  7         #region 成员
  8 
  9         /// <summary>
 10         /// Post数据请求
 11         /// </summary>
 12         StringBuilder _postData = new StringBuilder();
 13 
 14         #endregion
 15 
 16         #region 事件
 17 
 18         /// <summary>
 19         /// 为DownloadStringCompleted 事件声明的委托
 20         /// </summary>
 21         /// <param name="sender">触发事件的对象</param>
 22         /// <param name="e">持有已下载好的数据的参数</param>
 23         public delegate void DownloadStringCompletedHandler(object sender, DownloadStringCompletedEventArgs e);
 24 
 25         /// <summary>
 26         /// 当异步资源下载操作完成是触发
 27         /// </summary>
 28         public event DownloadStringCompletedHandler DownloadStringCompleted;
 29 
 30         #endregion
 31 
 32         #region 构造方法
 33 
 34         /// <summary>
 35         /// 创建一个包含特殊参数的PostClient实例
 36         /// </summary>
 37         /// <param name="parameters">String格式的Post 参数。有效的字符串格式形如:“name=David&amp;psd=123456”</param>
 38         public PostClient(string parameters)
 39         {
 40             _postData.Append(parameters);
 41         }
 42 
 43         /// <summary>
 44         /// 创建一个包含特殊参数的PostClient实例
 45         /// </summary>
 46         /// <param name="parameters">String列表格式的Post 参数。有效的字符串格式形如:“name=Divad”</param>
 47         public PostClient(IList<string> parameters)
 48         {
 49             foreach (var element in parameters)
 50             {
 51                 _postData.Append(string.Format("{0}&",element));
 52             }
 53         }
 54 
 55         /// <summary>
 56         /// 创建一个包含特殊参数的PostClient实例
 57         /// </summary>
 58         /// <param name="parameters">字典格式的Post参数,有效的字典格式形如:“<"name","Divad">,<"psd",123456></param>
 59         public PostClient(IDictionary<string, object> parameters)
 60         {
 61             foreach (var pair in parameters)
 62             {
 63                 _postData.Append(string.Format("{0}={1}&",pair.Key,pair.Value));
 64             }
 65         }
 66         #endregion
 67 
 68         #region 公有方法
 69 
 70         /// <summary>
 71         /// 从string格式的指定Uri中下载资源
 72         /// </summary>
 73         /// <param name="address">提供资源的URi地址</param>
 74         public void DownloadStringAsync(Uri address)
 75         {
 76             HttpWebRequest request;
 77 
 78             try
 79             {
 80                 request = (HttpWebRequest)WebRequest.Create(address);
 81                 request.Method = "POST";
 82                 request.ContentType = "application/x-www-form-urlencoded";
 83                 request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
 84             }
 85             catch 86             {
 87                 if (DownloadStringCompleted!=null)
 88                 {
 89                     System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
 90                     {
 91                         DownloadStringCompleted(this,new DownloadStringCompletedEventArgs(new Exception("创建HTTP POST请求时发生错误")));
 92                     });
 93                 }
 94                 throw;
 95             }
 96         }
 97 
 98         #endregion
 99 
100         #region 私有方法
101 
102         /// <summary>
103         /// 执行请求时准备执行的操作
104         /// </summary>
105         /// <param name="asyncResult">异步操作状态</param>
106         private void RequestReady(IAsyncResult asyncResult)
107         {
108             HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
109 
110             using (Stream stream=request.EndGetRequestStream(asyncResult))
111             {
112                 using (StreamWriter writer=new StreamWriter(stream))
113                 {
114                     writer.Write(_postData.ToString());
115                     writer.Flush();
116                 }
117             }
118 
119             request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
120         }
121 
122         /// <summary>
123         /// 请求响应是准备执行的操作
124         /// </summary>
125         /// <param name="asyncResult"></param>
126       private void ResponseReady(IAsyncResult asyncResult)
127         {
128             HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
129             HttpWebResponse response = null;
130 
131             try
132             {
133                 response = (HttpWebResponse)request.EndGetResponse(asyncResult);
134 
135                 string result = string.Empty;
136                 using (Stream responseStream=response.GetResponseStream())
137                 {
138                     using (StreamReader reader=new StreamReader(responseStream))
139                     {
140                         result = reader.ReadToEnd();
141                     }
142                 }
143 
144                 if (DownloadStringCompleted!=null)
145                 {
146                     System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
147                     {
148                         DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(result));
149                     });
150                 }
151             }
152             catch 
153             {
154 
155                 if (DownloadStringCompleted!=null)
156                 {
157                     System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
158                     { 
159                         DownloadStringCompleted(this,new DownloadStringCompletedEventArgs(new Exception("获取HTTP网络请求时发生错误!")));
160                     });
161                 }
162             }
163         }
164         #endregion
165     }
posted @ 2012-07-17 13:06  denjuy  阅读(318)  评论(0编辑  收藏  举报