在WebClient中使用post[發送資料]

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   strong   io   

很多時候,我們需要使用C#中的WebClient 來收發資料,WebClient 類提供向 URI 標識的任何本地、Intranet 或 Internet 資源發送資料以及從這些資源接收資料的公用方法。

 

  下面先說說WebClient 最主要的功能。
   
  WebClient 建構函式

 .Ctor 包括 一個空建構函式 和一個靜態建構函式, 靜態建構函式主要為UrlEncode 和UrlEncodeAndWirte 編碼提供參照byte[]資料的初始化作用。

      stati WebClient()

      public WebClient() 

 WebClient提供四種將資料上傳到資源的方法:

  • OpenWrite 返回一個用於將資料發送到資源的 Stream。
  • UploadData 將位元組數組發送到資源並返回包含任何響應的位元組數組。
  • UploadFile 將本地檔案發送到資源並返回包含任何響應的位元組數組。
  • UploadValues 將 NameValueCollection 發送到資源並返回包含任何響應的位元組數組。

WebClient還提供三種從資源下載資料的方法:

  • DownloadData 從資源下載資料並返回位元組數組。
  • DownloadFile 從資源將資料下載到本地檔案。
  • OpenRead 從資源以 Stream 的形式返回資料。
瞭解了WebClient的知識後,我們開始正式進入正題。
通過Post方式發送資料可以避免Get方式的資料長度限制,下面採用WebClient來實現這個功能。Web服務端可以是任何CGI但是要搞清楚Web端接受的編碼,代碼如下:

   WebClient wc = new WebClient();    StringBuilder postData = new StringBuilder();    postData.Append("formField1=" + "表單資料一");    postData.Append("&formField2=" + "表單資料二");    postData.Append("&formField3=" + "表單資料三");    //下面是GB2312編碼    byte[] sendData = Encoding.GetEncoding("GB2312").GetBytes(postData.ToString());    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");    wc.Headers.Add("ContentLength", sendData.Length.ToString());    byte[] recData= wc.UploadData("http://www.domain.cn/services/DataImport1.asp","POST",sendData);    //顯示傳回值注意編碼    MessageBox.Show(Encoding.GetEncoding("GB2312").GetString(recData));

注意"表單資料x"中包含如 "&","=","+"時需要使用,
HttpUtility.UrlEncode( "+++xxx為什麼不編碼也可以",Encoding.GetEncoding("GB2312")) 進行編碼
HttpUtility.UrlEncode(string) 預設使用UTF-8進行編碼,因此使用 UrlEncode編碼時並且欄位裡有中文,並且目標網站使用GB2312時,需要在UrlEncode函數中指明使用Gb2312
這樣上面的拼接代碼可以修改為如下:
postData.Append("formField1=" +  HttpUtility.UrlEncode("表單資料一",Encoding.GetEncoding("GB2312")));
postData.Append("&formField2=" +  HttpUtility.UrlEncode("表單資料二",Encoding.GetEncoding("GB2312")));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.