Silverlight HttpUtil 封裝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;
using System.IO;
using System.Threading;
using System.Text;


namespace Navi
{
    /*
     * 鍾磊 20111127
     * 
     * 封裝silverlight 中的Http Post調用
     *          
     * 使用時需要在應用的第一個構造函數中添加語句,否則無法取到Http響應頭
     * 
     * bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
     * 
     * 形如:
     * 
     * public MainPage()
       {
            //For Get Http Header
            bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);


            InitializeComponent();
     * }
     */


    public class HttpUtil
    {
        /*
         * * 
         * HTTP_CALLBACK 用戶調用傳入的回調函數
         * success 調用是否成功
         * compress 返回的stream是否是zip過的
         * flag 調用時傳入的標記,用以在調用端區分是哪一個的回調
         * responseStream,Http響應傳回的流
         */




        public delegate void HTTP_CALLBACK(bool success, bool compress, string flag, Stream responseStream);


        private byte[] _postData = null;
        private SynchronizationContext _syncContext = null;
        private HTTP_CALLBACK _cb = null;
        private string _flag;//當前調用的動作
    


        public HttpUtil(){}




        public void Post(string strPara, string strUrl, string strFlag, HTTP_CALLBACK cb)
        {
            //保存當前調用線程上下文(用戶線程)
            _syncContext = SynchronizationContext.Current;
            _cb = cb;
            _postData = Encoding.UTF8.GetBytes(strPara);
            _flag = strFlag;


            Uri endpoint = new Uri(strUrl, UriKind.Absolute);
            HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
            request.Method = "POST";
            IAsyncResult asyncResult = request.BeginGetRequestStream(
                new AsyncCallback(callback_resuest), request);
        }


        private  void callback_resuest(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            request.ContentType = "application/x-www-form-urlencoded";
            Stream requestStream = request.EndGetRequestStream(result);
            requestStream.Write(_postData, 0, _postData.Length);
            requestStream.Close();
            request.BeginGetResponse(new AsyncCallback(callback_response), request);           
        }


        private void callback_response(IAsyncResult asyncResult)
        {          
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            WebResponse response = request.EndGetResponse(asyncResult);


            //回調界面,返回用戶線程
            _syncContext.Post(callback_ui, response);          
        }




        private void callback_ui(object state)
        {
            HttpWebResponse response = state as HttpWebResponse;                        


            //與服務端約定返回數據是否壓縮(ZIP)標誌
            bool compress = (response.Headers["COMPRESS"].ToUpper() == "TRUE");


            //與服務端約定的成功標誌
            bool success = (response.Headers["RESULT_CODE"].ToUpper() == "OK");


            //回調
            _cb(success,compress,_flag,response.GetResponseStream());
                        
            response.GetResponseStream().Close();
            response.Close();                        
        }
    }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//這樣調用

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Threading;
using System.IO;
using Navi;
using System.Net.Browser;




namespace Silverlight_HttpDemo
{
   
    public partial class MainPage : UserControl
    {
        private string para = @"
SQL=select * from sys_czyb where rownum < 3
&USER=app_user
&CHARSET=UTF-8
&FUN=select
&COMPRESS=true
&SPLITE_ROW=|
&SPLITE_COL=^
";


        private string url = "http://10.111.43.18:8099/pmias/servlet/db_proc_common";


        


        public MainPage()
        {
            //For Get Http Header
            bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);


            InitializeComponent();


            para = para.Replace("\r\n", "");
        }
                      
        //請求獲取文本
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            new HttpUtil().Post(para, url, "GET_TXT", this.http_cb);            
        }


        //請求獲取數據後保存
        Stream savefile;
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog();
            
            if (sf.ShowDialog() == true)
            {
                savefile = sf.OpenFile();
                new HttpUtil().Post(para,url,"SAVE_FILE",this.http_cb);
            }
        }


        //回調函數
        private void http_cb(Boolean success,bool compress,string flag,Stream responseStream)
        {
            String fmt = @"成功:{0}
壓縮:{1}
內容:{2}";
            string content = "未定義";


            switch (flag)
            {
                case "SAVE_FILE":
                    {                        
                        if (success == false)
                        {               
                            //失敗,不寫入文件,取出錯誤信息
                            if (compress)
                                content = ZipUtil.ZipStream2String(responseStream);
                            else
                                content = ZipUtil.Stream2String(responseStream);


                            savefile.Close();                            
                        }
                        else
                        {


                            //成功,將返回的流寫入文件
                            if (compress)
                                ZipUtil.ZipStream2File(savefile, responseStream);
                            else
                                ZipUtil.Stream2File(savefile, responseStream);
                            savefile.Close();


                            content = "成功";                            
                        }


                        content = String.Format(fmt, success, compress, content);
                        
                    }
                    break;
                case "GET_TXT":
                    {                        
                        if (compress)
                            content = ZipUtil.ZipStream2String(responseStream);
                        else
                            content = ZipUtil.Stream2String(responseStream);
                        
                        content = String.Format(fmt, success, compress, content);                        
                    }                                     
                    break;
                default:
                    MessageBox.Show("錯誤的flag:"+flag);
                    break;
            }
            MessageBox.Show(content, "提示", MessageBoxButton.OK);
            
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章