Winform中使用WebClient連網處理資料

來源:互聯網
上載者:User

這兩天,遇到了一個winform連網擷取資料的問題,於是從網上搜了些資料學習了一下,完了之後,也不能忘記總結。下面我就簡單談一下WebClient類的常見用法。

 首先,我先談一下我對WebClient類中這些方法的操作方式的看法。我想,很多人可能跟我一樣,覺得MSDN對這個類的很多解釋和案例都讓人看起來覺得蛋疼,因為,解釋的比較含糊(或者說比較官方),舉得例子吧,也太簡單了,並且,只有用戶端的代碼,沒有伺服器端的代碼。這些東西都讓人覺得WebClient這種操作方式挺神秘的。其實,真的沒有什麼神秘的。伺服器端,就是一個網頁(這個就是讓人不知為何物的CRI資源),這個網頁就跟一般的網頁只有一點不一樣,就是,如果需要向用戶端返回資料的話,用Response.write()方法輸出,這樣子就能被用戶端擷取到了。至於為什麼能被用戶端擷取到,那我就不曉得了,這個問題得去問微軟。用戶端的代碼,比較簡單無非就是字串啊,流啊,等。兩種提交的方式有必要說一下,一種是同步,一種是非同步。這種方式,比較適合於案頭軟體連網訪問資料庫。其實,是案頭軟體訪問某個你做好的頁面,把某些參數傳到那個頁面中,然後,你在那個網頁中,根據傳遞過來的參數,把某些跟資料庫有關的商務邏輯處理一下,然後再返回用戶端。下面,我貼出來一些代碼,以便更好地理解WebClient。 功能一:向伺服器提交資料: 用戶端代碼:    private void btn_sent_Click(object sender, EventArgs e)        {           string data = this.textBox1.Text.ToString();             Uri endpoint = new Uri("http://localhost:3778/Default2.aspx");//這個你可以根據自己的本地連接埠修改             WebClient client = new WebClient();            client.Encoding = Encoding.UTF8;            //這是一種非同步執行的方法,當資料下載完之後,會觸發UploadStringCompleted 事件,            //   所以,我們註冊這個事件            client.UploadStringCompleted +=            new UploadStringCompletedEventHandler(client_UploadStringCompleted);            client.UploadStringAsync(endpoint, "POST", data);      }        /// <summary>        /// 下載完資料之後,就會調用這個方法        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>     void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)        {            MessageBox.Show(e.Result);        }   伺服器端代碼:      protected void Page_Load(object sender, EventArgs e)        {            //擷取從用戶端傳來的資訊               int length = Request.ContentLength;            byte[] bytes = Request.BinaryRead(length);             string txtContent =System.Text.Encoding.UTF8.GetString(bytes);                        //伺服器在這裡可以完成商務邏輯。舉個例子,如果從用戶端傳過來一條SQL語句,            //那麼,在這裡就可以執行這條Sql語句。                        //從伺服器端返回資訊               Response.ContentType = "text/plain";            Response.Write(txtContent);        }    功能二:根據某些參數,從伺服器檢索資料,並接受該資料 用戶端代碼:             string tranType = "TextStr";//第一個參數             sting tranType="weather"; //第二個參數。這兩個參數可以根據具體的邏輯改寫            Uri endpoint = new Uri(String.Format("http://localhost:3778/Default.aspx?infoType=                {0}&tranType={1}", infoType, tranType));            WebClient client = new WebClient();            client.Encoding = Encoding.UTF8;                       client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);             client.DownloadStringAsync(endpoint);  void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)        {            string RetStr = "";            if (e.Error == null)            {                //RetStr = "WebClient成功通訊";                RetStr = e.Result;               }            else            {                RetStr = e.Error.Message;            }            MessageBox.Show( RetStr);  //顯示操作結果資訊         }  伺服器端代碼:      protected void Page_Load(object sender, EventArgs e)        {            //讀取從用戶端傳遞過來的參數               string infoTypeStr = Request.QueryString["infoType"];            string tranTypeStr = Request.QueryString["tranType"];            //根據參數,做一些相應的商務邏輯            string  retValueStr  ="處理邏輯後的返回結果";            Response.ContentType = "text/plain";            Response.Write(retValueStr);          }   這兩個功能,請參考http://blog.csdn.net/longlong821/article/details/7187524 。 功能三:想伺服器上傳檔案這個思想就是把檔案轉換成流的形式,然後發送到伺服器端。用戶端代碼: WebClient client = new WebClient(); sting uriString="http://localhost:3778/Default2.aspx";string fileName="D:\\1.txt"; //你要給些這個檔案路徑myWebClient.UploadFile(uriString, fileName);  伺服器端: private void Page_Load(object sender, System.EventArgs e)
 {   // 擷取 http提交上傳的檔案, 並改名儲存
      foreach (string key in Request.Files.AllKeys)
      {
         HttpPostedFile file = Request.Files[key];
         string newFilename = DateTime.Now.ToString("yyMMddhhmmssffff")
                + file.FileName.Substring(file.FileName.LastIndexOf('.'));

            try
            {   //檔案儲存並返回相對路徑地址
                file.SaveAs(this.serverPath + newFilename);
                Response.Write("upload/" + newFilename);
            }
            catch (Exception)
            {                
            }
        }
    } 上傳檔案部分請參見 http://www.blogjava.net/kiant/articles/277929.html 。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.