以Post方式發送資料採用WebClient

來源:互聯網
上載者:User
通過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.