因工作需要,需要开发wp7手机程序,在手机中模拟HTTP请求,发送请求。然后获取请求后的数据,
其实微软的类库已经提供好了相应的类库,不过我想更方便的操作HTTP请求,我们知道HTTP请求分为
两种,一种GET,一种POST;不过那种方式,我们经常的需要进行参数的添加。为了更方便操作,编写
我自己的类库,方便自己的HTTP请求和追加参数。同时为了获取请求的结果,我自己封装了httpCompleted
事件,这样就方便了用户获取HTTP的请求结果,其实这些都是雕虫小计。代码中含有注释,看懂应该不难。
代码如下:
- using System;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using System.IO;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- namespace testHttpPost
- {
- ///
- /// winphone7的HTTP封装类
- ///
- public class WP7HttpRequest
- {
- #region 私有成员
- private string _request_url = null;
- private requestType _request_type;
- IDictionary<string, string> _parameter;
- #endregion
- ///
- /// Http请求指代
- ///
- /// 发送者
- /// 发送所带的参数
- public delegate void httpResquestEventHandler(object sender, WP7HttpEventArgs e);
- ///
- /// Http请求完成事件
- ///
- public event httpResquestEventHandler httpCompleted;
- ///
- /// 默认构造函数
- ///
- ///
- /// 默认的请求方式的GET
- ///
- public WP7HttpRequest()
- {
- _request_url = "";
- _parameter = new Dictionary<string, string>();
- _request_type = requestType.GET; //默认请求方式为GET方式
- }
- ///
- /// 追加就参数
- ///
- /// 进行追加的键
- /// 键对应的值
- public void appendParameter(string key, string value)
- {
- _parameter.Add(key, value);
- }
- ///
- /// 触发HTTP请求完成方法
- ///
- /// 事件参数
- public void OnHttpCompleted(WP7HttpEventArgs e)
- {
- if (this.httpCompleted != null)
- {
- this.httpCompleted(this, e);
- }
- }
- ///
- /// 请求URL地址
- ///
- public string requestUrl
- {
- get { return _request_url; }
- set { _request_url = value; }
- }
- ///
- /// 请求方式
- ///
- public requestType requestMethod
- {
- get { return _request_type; }
- set { _request_type = value; }
- }
- ///
- /// 进行HTTP请求
- ///
- public void request()
- {
- if (this.requestMethod == requestType.GET)
- {
- this.getRequest();
- }
- else
- {
- this.postRequest();
- }
- }
- ///
- /// HTTP方式的GET请求
- ///
- ///
- private void getRequest()
- {
- string strrequesturl = this.requestUrl;
- string parastring = this.getParemeterString();
- if (parastring.Length > 0)
- {
- strrequesturl += "?" + parastring;
- }
- Uri myurl = new Uri(strrequesturl);
- HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myurl);
- webRequest.Method = "GET";
- webRequest.BeginGetResponse(new AsyncCallback(handleResponse), webRequest); //直接获取响应
- _parameter.Clear(); //清空参数列表
- }
- ///
- /// HTTP的POST请求
- ///
- ///
- private void postRequest()
- {
- Uri myurl = new Uri(this.requestUrl);
- HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myurl);
- webRequest.ContentType = "application/x-www-form-urlencoded";
- webRequest.Method = "POST";
- webRequest.BeginGetRequestStream(new AsyncCallback(handlePostReady), webRequest);
- }
- ///
- /// 获取传递参数的字符串
- ///
- /// 字符串
- private string getParemeterString()
- {
- string result = "";
- StringBuilder sb = new StringBuilder();
- bool hasParameter = false;
- string value = "";
- foreach (var item in _parameter)
- {
- if (!hasParameter)
- hasParameter = true;
- value = UrlEncoder.Encode(item.Value); //对传递的字符串进行编码操作
- sb.Append(string.Format("{0}={1}&", item.Key, value));
- }
- if (hasParameter)
- {
- result = sb.ToString();
- int len = result.Length;
- result = result.Substring(0, --len); //将字符串尾的‘&’去掉
- }
- return result;
- }
- ///
- /// 异步请求回调函数
- ///
- /// 异步请求参数
- private void handlePostReady(IAsyncResult asyncResult)
- {
- HttpWebRequest webRequest = asyncResult.AsyncState as HttpWebRequest;
- using (Stream stream = webRequest.EndGetRequestStream(asyncResult))
- {
- using (StreamWriter writer = new StreamWriter(stream))
- {
- string parameterstring = this.getParemeterString();
- if (parameterstring.Length > 0)
- {
- writer.Write(this.getParemeterString());
- writer.Flush();
- }
- }
- }
- webRequest.BeginGetResponse(new AsyncCallback(handleResponse), webRequest);
- _parameter.Clear();//清空参数列表
- }
- ///
- /// 异步响应回调函数
- ///
- /// 异步请求参数
- private void handleResponse(IAsyncResult asyncResult)
- {
- string result = "";
- bool iserror = false;
- try
- {
- HttpWebRequest webRequest = asyncResult.AsyncState as HttpWebRequest;
- HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
- Stream streamResult = webResponse.GetResponseStream(); //获取响应流
- StreamReader reader = new StreamReader(streamResult);
- result = reader.ReadToEnd();
- }
- catch (Exception ex)
- {
- iserror = true;
- result = ex.Message;
- }
- finally
- {
- WP7HttpEventArgs e = new WP7HttpEventArgs();
- e.isError = iserror;
- e.result = result;
- //进行异步回调操作
- System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
- {
- OnHttpCompleted(e);
- });
- }
- }
- }
- ///
- /// 枚举请求类型
- ///
- public enum requestType
- {
- ///
- /// GET请求
- ///
- GET,
- ///
- /// POST请求
- ///
- POST
- }
- }
其中我自己定义的事件参数类,代码如下:
- using System;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- namespace testHttpPost
- {
- ///
- /// Http请求参数类
- ///
- public class WP7HttpEventArgs : EventArgs
- {
- #region 私有成员
- private string _result;
- private bool _is_error;
- #endregion
- ///
- /// 默认构造函数
- ///
- public WP7HttpEventArgs()
- {
- this.result = "";
- this.isError = false;
- }
- public WP7HttpEventArgs(string result)
- {
- this.result = result;
- this.isError = false;
- }
- ///
- /// 结果字符串
- ///
- public string result
- {
- get { return _result; }
- set { _result = value; }
- }
- ///
- /// 是否错误
- ///
- public bool isError
- {
- get { return _is_error; }
- set { _is_error = value; }
- }
- }
- }
经过自己的封装类,则在调用时,就非常的简单了,调用代码如下:
- void MainPage_Loaded(object sender, RoutedEventArgs e)
- {
- WP7HttpRequest request = new WP7HttpRequest();
- request.httpCompleted += new WP7HttpRequest.httpResquestEventHandler(request_httpCompleted);
- request.requestUrl = "";
- request.appendParameter("wd", "linux");
- request.requestMethod = requestType.GET;
- request.request();
- }
- void request_httpCompleted(object sender, WP7HttpEventArgs e)
- {
- this.textBlock1.Text = e.result;
- MessageBox.Show(e.result);
- }
测试代码 WP7HttpRequest.rar
阅读(3442) | 评论(0) | 转发(0) |