ITPub博客

首页 > Linux操作系统 > Linux操作系统 > WM6环境下测试通过的一个http request,response类

WM6环境下测试通过的一个http request,response类

原创 Linux操作系统 作者:freshairpeng 时间:2009-03-04 15:53:53 0 删除 编辑

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace CRM_Mobile.Util
{
    //Http get post方法
    class HttpService
    {
        //构造函数
        public HttpService()
        { }
        private static String fullname = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
        private static String myAppPath = System.IO.Path.GetDirectoryName(fullname);

        private string user_rowid = "2008022020821635 ";//用户名对应的row_id
        public string User
        {
            get { return user_rowid; }
            set { user_rowid = value; }
        }

        private string password = " ";//用户名对应的row_id
        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        private int suspage = -1;//上次成功的页码:第一次调用时该值为-1,依次递增。如:第一次传-1,第二次传0, 第三次传1…
        public int susPage
        {
            get { return suspage; }
            set { suspage = value; }
        }
        private string asynctype = "productInfo";//同步数据类型
        public string synType
        {
            get { return asynctype; }
            set { asynctype = value; }
        }
        private string pagesize = "6";//返回页条数
        public string pageSize
        {
            get { return pagesize; }
            set { pagesize = value; }
        }
        private string sn = "";//加密
        public string SN
        {
            get { return sn; }
            set { sn = value; }
        }
        private string ip = "61.129.250.73";//请求对应的服务器的IP地址
        public string IP
        {
            get { return ip; }
            set { ip = value; }
        }

        private int port = 9080;//端口号
        public int Port
        {
            get { return port; }
            set { port = value; }
        }
        //同步数据类型emum类型
        public enum Asynctype
        {
            custInfo,//客户信息
            contactInfo,//客户联系人
            productInfo,//产品列表
            salePrice,//销售品价格
            custContract,//客户合同
            oaContact,//OA合同
            saleOppGroup,//集团商机
            saleOppLocal,//本地网商机
            saleOppIct//ICT商机
        }

        // 建立 HttpWebRequest
        public HttpWebRequest CreateRequest(string address)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

            //request.Accept = "text/html,image/gif,text/xml,*/*";//指定客户接受的MIME类型的一个列表
            //request.Referer = "http://dotnetforce.com/default.aspx";//指定资源的地址,我们将从该地址获取所请求的url
            //request.UserAgent = "Mozilla/4.0(compatoble;MSIE 6.0;Windows NT 5.1;.NET CLR 1.0375)";//设置客户应用程序运行的平台
            //request.Timeout = 30;//设置超时连接时间
            //request.KeepAlive = false;//指示是否跟internet保持持久性连接 true代表是,默认为true
            //request.Connection = "close";//跟KeepAlive类似

            request.Method = "POST";//Http方法 GET POST HEAD COPY MOVE OPTIONS TRACE
            //request.Headers.Add("Keep-Alive", "false");
            request.ContentType = "application/x-www-form-urlencoded";
            return request;
        }
        //建立 WebRequest
        public WebRequest CreateWebRequest(string address)
        {
            WebRequest request = WebRequest.Create(address);
            request.Method = "POST";
            //request.Headers.Add("Keep-Alive", "false");
            request.ContentType = "application/x-www-form-urlencoded";
            return request;

        }
        //发送请求
        public bool SendRequest(HttpWebRequest httpwebrequest)
        {
            bool flag = true;
            try
            {
                //正式环境用
                //StringBuilder send = new StringBuilder();
                //send.Append("username" + HttpUtility.UrlEncode(this.username));
                //send.Append("password" + HttpUtility.UrlEncode(this.password));
                //send.Append("asynctype" + HttpUtility.UrlEncode(this.asynctype));

                string user = user_rowid;
                string synType = asynctype; ;
                int susPage = suspage;
                string pageSize = pagesize;
                StringBuilder send = new StringBuilder();
                send.Append("user=" + user);
                send.Append("&synType=" + synType);
                send.Append("&susPage=" + susPage);
                send.Append("&pageSize=" + pageSize);

 

                //测试用
                //string appId = "YahooDemo";
                //string context = "Italian sculptors and painters of the renaissance"
                //+ "favored the Virgin Mary for inspiration";
                //string query = "madonna";
                //StringBuilder send = new StringBuilder();
                //send.Append("appid=" + appId);
                //send.Append("&context=" + context);
                //send.Append("&query=" + query);


                byte[] byteData = UTF8Encoding.UTF8.GetBytes(send.ToString());

                httpwebrequest.ContentLength = byteData.Length;

                using (Stream postStream = httpwebrequest.GetRequestStream())
                {
                    postStream.Write(byteData, 0, byteData.Length);
                }
            }
            catch (Exception ex)
            {
                httpwebrequest.Abort();
                flag = false;
            }
            finally { }
            return flag;

        }
        //把从服务端获取的回应信息转化成字符串
        public string GetResponseToString(HttpWebRequest httpwebrequest)
        {
            string responsestr = "";
            using (HttpWebResponse response = (HttpWebResponse)httpwebrequest.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
                responsestr = reader.ReadToEnd();
            }
            return responsestr;
        }
        //把从服务端获取的回应信息转化成文件流
        public bool GetResponseToFile(HttpWebRequest request)
        {
            bool flag = true;
            FileStream fs = null;
            string filename = myAppPath + "\\" + @"TempXml.xml";
            try
            {

                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //Stream stream = response.GetResponseStream();
                //int length = (int)response.ContentLength;
                //BinaryReader br = new BinaryReader(stream);
                //FileStream fs;
                //fs = File.Create(filename);
                //fs.Write(br.ReadBytes(length), 0, length);
                //br.Close();
                //fs.Close();

                // Get response
                using (HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse())
                {
                    // Get the response stream
                    Stream streamresponse = webresponse.GetResponseStream();
             
                    int length = (int)webresponse.ContentLength;
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }

                    byte[] bytes = new byte[10240];
                    int n = 1;
                    fs = File.Create(filename);
                    while (n > 0)
                    {
                        n = streamresponse.Read(bytes, 0, 10240);
                        fs.Write(bytes, 0, n);
                    }
                    streamresponse.Close();
                    fs.Close();
                }

            }
            catch (Exception ex)
            {
                request.Abort();
               
                flag = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
             return flag;
        }

       }
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/14766526/viewspace-561380/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2009-02-25

  • 博文量
    69
  • 访问量
    247755