Post Operation for Windows 8 Apps || Windows Phone

简单实现HTTP Post & Get 请求操作, post 可用于文件或表单。此类适用于Windows 8 Apps 和 Windows phone.

HttpHelper
  1     /// <summary>
  2     /// Use for HTTP Post Method: send simple data or file
  3     /// </summary>
  4     public class HttpPostHelper
  5     {
  6         public void PostData(string postUrl, IDictionary<string, object> parameters)
  7         {
  8             string formDataBoundary = "-----------------------------525258000";
  9             string contentType = "multipart/form-data;boundary=" + formDataBoundary;
 10 
 11             _formData = GetFormData(parameters, formDataBoundary);
 12             ExcutePostRequest(postUrl, contentType);
 13         }
 14 
 15         private void ExcutePostRequest(string postUrl, string contentType)
 16         {
 17             var request = WebRequest.Create(postUrl) as HttpWebRequest;
 18 
 19             if (request == null)
 20             {
 21                 Debug.WriteLine("Request is not a request.");
 22             }
 23 
 24             request.Method = "POST";
 25             request.ContentType = contentType;
 26             request.BeginGetRequestStream(RequestReady, request);
 27         }
 28 
 29         private void RequestReady(IAsyncResult asyncResult)
 30         {
 31             var request = asyncResult.AsyncState as HttpWebRequest;
 32 
 33             if (request == null) return;
 34             using (Stream requestStream = request.EndGetRequestStream(asyncResult))
 35             {
 36                 requestStream.Write(_formData, 0, _formData.Length);
 37             }
 38 
 39             request.BeginGetResponse(ResponseReady, request);
 40         }
 41 
 42         private void ResponseReady(IAsyncResult asyncResult)
 43         {
 44             var request = asyncResult.AsyncState as HttpWebRequest;
 45 
 46             try
 47             {
 48                 var response = (HttpWebResponse) request.EndGetResponse(asyncResult);
 49                 string result;
 50                 using (var responseStream = response.GetResponseStream())
 51                 {
 52                     using (var reader = new StreamReader(responseStream))
 53                     {
 54                         result = reader.ReadToEnd();
 55                     }
 56                 }
 57 
 58                 if (DownloadStringCompleted != null)
 59                 {
 60                     DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(result));
 61                 }
 62             }
 63             catch
 64             {
 65                 if (DownloadStringCompleted != null)
 66                 {
 67                     DownloadStringCompleted(this,
 68                                             new DownloadStringCompletedEventArgs(
 69                                                 new Exception("Error getting HTTP web response.")));
 70                 }
 71             }
 72         }
 73 
 74         private static byte[] GetFormData(IEnumerable<KeyValuePair<string, object>> parameters, string boundary)
 75         {
 76             Stream formDataStream = new MemoryStream();
 77             var encoding = Encoding.UTF8;
 78             foreach (var param in parameters)
 79             {
 80                 if (param.Value is byte[])
 81                 {
 82                     var fileData = param.Value as byte[];
 83 
 84                     string header =
 85                         string.Format(
 86                             "--{0}\r\nContent-Disposition:form-data;name=\"file\";filename=\"{1}\";\r\nContent-Type:application/zip\r\n\r\n",
 87                             boundary, param.Key);
 88                     formDataStream.Write(encoding.GetBytes(header), 0, header.Length);
 89                     formDataStream.Write(fileData, 0, fileData.Length);
 90                 }
 91                 else
 92                 {
 93                     string postData = string.Format(
 94                         "--{0}\r\nContent-Disposition:form-data;name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key,
 95                         param.Value);
 96                     formDataStream.Write(encoding.GetBytes(postData), 0, postData.Length);
 97                 }
 98             }
 99             string footer = "\r\n--" + boundary + "--\r\n";
100             formDataStream.Write(encoding.GetBytes(footer), 0, footer.Length);
101 
102             formDataStream.Position = 0;
103             var formData = new byte[formDataStream.Length];
104             formDataStream.Read(formData, 0, formData.Length);
105             formDataStream.Dispose();
106 
107             return formData;
108         }
109 
110         public delegate void DownloadStringCompletedHandler(object sender, DownloadStringCompletedEventArgs e);
111 
112         public event DownloadStringCompletedHandler DownloadStringCompleted;
113 
114         private byte[] _formData = null;
115     }
116 
117     /// <summary>
118     /// Use for HTTP Get Method 
119     /// </summary>
120     public class HttpGetHelper
121     {
122         public void ExecuteGetReuqest(string url)
123         {
124             var request = WebRequest.Create(url) as HttpWebRequest;
125 
126             if (request == null)
127             {
128                 Debug.WriteLine("Request is not a request.");
129             }
130             else
131             {
132                 request.BeginGetResponse(ResponseReady, request);
133             }
134         }
135 
136         private void ResponseReady(IAsyncResult asyncResult)
137         {
138             try
139             {
140                 var request = (HttpWebRequest) asyncResult.AsyncState;
141                 var response = (HttpWebResponse) request.EndGetResponse(asyncResult);
142                 string result;
143                 using (var responseStream = response.GetResponseStream())
144                 {
145                     using (var reader = new StreamReader(responseStream))
146                     {
147                         result = reader.ReadToEnd();
148                     }
149                 }
150 
151                 if (DownloadStringCompleted != null)
152                 {
153                     DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(result));
154                 }
155             }
156             catch
157             {
158                 if (DownloadStringCompleted != null)
159                 {
160                     DownloadStringCompleted(this,
161                                             new DownloadStringCompletedEventArgs(
162                                                 new Exception("Error getting HTTP web response.")));
163                 }
164             }
165         }
166 
167         public delegate void DownloadStringCompletedHandler(object sender, DownloadStringCompletedEventArgs e);
168 
169         public event DownloadStringCompletedHandler DownloadStringCompleted;
170     }
171 
172     public class DownloadStringCompletedEventArgs : EventArgs
173     {
174         public DownloadStringCompletedEventArgs(string result)
175         {
176             Result = result;
177         }
178 
179         public DownloadStringCompletedEventArgs(Exception ex)
180         {
181             Error = ex;
182         }
183 
184         public string Result { get; private set; }
185         public Exception Error { get; private set; }
186     }
posted @ 2012-11-27 15:03  denjuy  阅读(401)  评论(4编辑  收藏  举报