標籤: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")));