天天看點

WebClient 類的使用(二)

在WebClient 類的使用(一)中,僅僅是實作了傳普通的字元串,而且,有點讓我感覺不爽的是,當我要傳許多的值的時候,要在按鈕事件中拼接所有資料成為一個字元串,然後在轉化成相應的byte[]資料,也太不爽了吧。而且條理性也不強。于是繼續檢視幫助文檔,發現有一新方法,很使用。這個方法就是:UploadValues()方法。

1.前台代碼,跟(一)中的相同,不在貼出。

2.相應的背景處理按鈕的代碼。

// 請求按鈕

        protected void btnSend_Click(object sender, EventArgs e)

        {

            string url = txt_url.Value.Trim();

            string name=txt_name.Value.Trim();

            string sex = txt_sex.Value.Trim();

            WebClient myWebClient = new WebClient();

            // 設定編碼格式

            myWebClient.Encoding = Encoding.UTF8;

            // 要post的參數

            NameValueCollection PostVars = new NameValueCollection();

            PostVars.Add("Name", name);

            PostVars.Add("Sex", sex);

            byte[] resultData = myWebClient.UploadValues(url, PostVars);

            string strResult = Encoding.UTF8.GetString(resultData);

        }

注:背景的處理按鈕事件中,進行處理。

3.伺服器處理頁面的處理。

protected void Page_Load(object sender, EventArgs e)

        {

            string name = Request["Name"].ToString();

            string sex = Request["Sex"].ToString();

            // 接受到參數,進行相應處理

            //string reqStr =Encoding.UTF8.GetString(reqByte);

            // 傳回資訊

            Response.Write("成功");

            Response.End();

        }