Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2538826
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: 嵌入式

2012-05-31 10:18:02

    因工作需要,需要开发wp7手机程序,在手机中模拟HTTP请求,发送请求。然后获取请求后的数据,
其实微软的类库已经提供好了相应的类库,不过我想更方便的操作HTTP请求,我们知道HTTP请求分为
两种,一种GET,一种POST;不过那种方式,我们经常的需要进行参数的添加。为了更方便操作,编写
我自己的类库,方便自己的HTTP请求和追加参数。同时为了获取请求的结果,我自己封装了httpCompleted
事件,这样就方便了用户获取HTTP的请求结果,其实这些都是雕虫小计。代码中含有注释,看懂应该不难。
代码如下:

点击(此处)折叠或打开

  1. using System;
  2. using System.Net;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Documents;
  6. using System.Windows.Ink;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Animation;
  10. using System.Windows.Shapes;

  11. using System.IO;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using System.Text;
  15. namespace testHttpPost
  16. {
  17.     ///
  18.     /// winphone7的HTTP封装类
  19.     ///
  20.     public class WP7HttpRequest
  21.     {
  22.         #region 私有成员

  23.         private string _request_url = null;
  24.         private requestType _request_type;
  25.         IDictionary<string, string> _parameter;

  26.         #endregion

  27.         ///
  28.         /// Http请求指代
  29.         ///
  30.         /// 发送者
  31.         /// 发送所带的参数
  32.         public delegate void httpResquestEventHandler(object sender, WP7HttpEventArgs e);

  33.         ///
  34.         /// Http请求完成事件
  35.         ///
  36.         public event httpResquestEventHandler httpCompleted;

  37.         ///
  38.         /// 默认构造函数
  39.         ///
  40.         ///
  41.         /// 默认的请求方式的GET
  42.         ///
  43.         public WP7HttpRequest()
  44.         {
  45.             _request_url = "";
  46.             _parameter = new Dictionary<string, string>();
  47.             _request_type = requestType.GET; //默认请求方式为GET方式
  48.         }

  49.         ///
  50.         /// 追加就参数
  51.         ///
  52.         /// 进行追加的键
  53.         /// 键对应的值
  54.         public void appendParameter(string key, string value)
  55.         {
  56.             _parameter.Add(key, value);
  57.         }

  58.         ///
  59.         /// 触发HTTP请求完成方法
  60.         ///
  61.         /// 事件参数
  62.         public void OnHttpCompleted(WP7HttpEventArgs e)
  63.         {
  64.             if (this.httpCompleted != null)
  65.             {
  66.                 this.httpCompleted(this, e);
  67.             }
  68.         }

  69.         ///
  70.         /// 请求URL地址
  71.         ///
  72.         public string requestUrl
  73.         {
  74.             get { return _request_url; }
  75.             set { _request_url = value; }
  76.         }

  77.         ///
  78.         /// 请求方式
  79.         ///
  80.         public requestType requestMethod
  81.         {
  82.             get { return _request_type; }
  83.             set { _request_type = value; }
  84.         }

  85.         ///
  86.         /// 进行HTTP请求
  87.         ///
  88.         public void request()
  89.         {
  90.             if (this.requestMethod == requestType.GET)
  91.             {
  92.                 this.getRequest();
  93.             }
  94.             else
  95.             {
  96.                 this.postRequest();
  97.             }
  98.         }

  99.         ///
  100.         /// HTTP方式的GET请求
  101.         ///
  102.         ///
  103.         private void getRequest()
  104.         {
  105.             string strrequesturl = this.requestUrl;
  106.             string parastring = this.getParemeterString();
  107.             if (parastring.Length > 0)
  108.             {
  109.                 strrequesturl += "?" + parastring;
  110.             }
  111.             Uri myurl = new Uri(strrequesturl);
  112.             HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myurl);
  113.             webRequest.Method = "GET";
  114.             webRequest.BeginGetResponse(new AsyncCallback(handleResponse), webRequest); //直接获取响应
  115.             _parameter.Clear(); //清空参数列表
  116.         }

  117.         ///
  118.         /// HTTP的POST请求
  119.         ///
  120.         ///
  121.         private void postRequest()
  122.         {
  123.             Uri myurl = new Uri(this.requestUrl);
  124.             HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myurl);
  125.             webRequest.ContentType = "application/x-www-form-urlencoded";
  126.             webRequest.Method = "POST";
  127.             webRequest.BeginGetRequestStream(new AsyncCallback(handlePostReady), webRequest);
  128.         }

  129.         ///
  130.         /// 获取传递参数的字符串
  131.         ///
  132.         /// 字符串
  133.         private string getParemeterString()
  134.         {
  135.             string result = "";
  136.             StringBuilder sb = new StringBuilder();
  137.             bool hasParameter = false;
  138.             string value = "";
  139.             foreach (var item in _parameter)
  140.             {
  141.                 if (!hasParameter)
  142.                     hasParameter = true;
  143.                 value = UrlEncoder.Encode(item.Value); //对传递的字符串进行编码操作
  144.                 sb.Append(string.Format("{0}={1}&", item.Key, value));
  145.             }
  146.             if (hasParameter)
  147.             {
  148.                 result = sb.ToString();
  149.                 int len = result.Length;
  150.                 result = result.Substring(0, --len); //将字符串尾的‘&’去掉
  151.             }
  152.             return result;

  153.         }

  154.         ///
  155.         /// 异步请求回调函数
  156.         ///
  157.         /// 异步请求参数
  158.         private void handlePostReady(IAsyncResult asyncResult)
  159.         {
  160.             HttpWebRequest webRequest = asyncResult.AsyncState as HttpWebRequest;
  161.             using (Stream stream = webRequest.EndGetRequestStream(asyncResult))
  162.             {
  163.                 using (StreamWriter writer = new StreamWriter(stream))
  164.                 {
  165.                     string parameterstring = this.getParemeterString();
  166.                     if (parameterstring.Length > 0)
  167.                     {
  168.                         writer.Write(this.getParemeterString());
  169.                         writer.Flush();
  170.                     }
  171.                 }
  172.             }
  173.             webRequest.BeginGetResponse(new AsyncCallback(handleResponse), webRequest);
  174.             _parameter.Clear();//清空参数列表
  175.         }

  176.         ///
  177.         /// 异步响应回调函数
  178.         ///
  179.         /// 异步请求参数
  180.         private void handleResponse(IAsyncResult asyncResult)
  181.         {
  182.             string result = "";
  183.             bool iserror = false;
  184.             try
  185.             {
  186.                 HttpWebRequest webRequest = asyncResult.AsyncState as HttpWebRequest;
  187.                 HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
  188.                 Stream streamResult = webResponse.GetResponseStream(); //获取响应流
  189.                 StreamReader reader = new StreamReader(streamResult);
  190.                 result = reader.ReadToEnd();
  191.             }
  192.             catch (Exception ex)
  193.             {
  194.                 iserror = true;
  195.                 result = ex.Message;
  196.             }
  197.             finally
  198.             {
  199.                 WP7HttpEventArgs e = new WP7HttpEventArgs();
  200.                 e.isError = iserror;
  201.                 e.result = result;
  202.                 //进行异步回调操作
  203.                 System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
  204.                 {

  205.                     OnHttpCompleted(e);

  206.                 });
  207.             }
  208.         }
  209.     }

  210.     ///
  211.     /// 枚举请求类型
  212.     ///
  213.     public enum requestType
  214.     {
  215.         ///
  216.         /// GET请求
  217.         ///
  218.         GET,

  219.         ///
  220.         /// POST请求
  221.         ///
  222.         POST
  223.     }
  224. }
其中我自己定义的事件参数类,代码如下:

点击(此处)折叠或打开

  1. using System;
  2. using System.Net;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Documents;
  6. using System.Windows.Ink;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Animation;
  10. using System.Windows.Shapes;

  11. namespace testHttpPost
  12. {
  13.     ///
  14.     /// Http请求参数类
  15.     ///
  16.     public class WP7HttpEventArgs : EventArgs
  17.     {
  18.         #region 私有成员

  19.         private string _result;
  20.         private bool _is_error;

  21.         #endregion

  22.         ///
  23.         /// 默认构造函数
  24.         ///
  25.         public WP7HttpEventArgs()
  26.         {
  27.             this.result = "";
  28.             this.isError = false;
  29.         }

  30.         public WP7HttpEventArgs(string result)
  31.         {
  32.             this.result = result;
  33.             this.isError = false;
  34.         }

  35.         ///
  36.         /// 结果字符串
  37.         ///
  38.         public string result
  39.         {
  40.             get { return _result; }
  41.             set { _result = value; }
  42.         }

  43.         ///
  44.         /// 是否错误
  45.         ///
  46.         public bool isError
  47.         {
  48.             get { return _is_error; }
  49.             set { _is_error = value; }
  50.         }
  51.     }
  52. }
经过自己的封装类,则在调用时,就非常的简单了,调用代码如下:

点击(此处)折叠或打开

  1. void MainPage_Loaded(object sender, RoutedEventArgs e)
  2.         {
  3.             WP7HttpRequest request = new WP7HttpRequest();
  4.             request.httpCompleted += new WP7HttpRequest.httpResquestEventHandler(request_httpCompleted);
  5.             request.requestUrl = "";
  6.             request.appendParameter("wd", "linux");
  7.             request.requestMethod = requestType.GET;
  8.             request.request();
  9.         }

  10.         void request_httpCompleted(object sender, WP7HttpEventArgs e)
  11.         {
  12.             this.textBlock1.Text = e.result;
  13.             MessageBox.Show(e.result);
  14.         }
测试代码 WP7HttpRequest.rar
阅读(3442) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~