WM6環境下測試通過的一個http request,response類

freshairpeng發表於2009-03-04

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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章