以Post方式发送数据采用WebClient
生活随笔
收集整理的這篇文章主要介紹了
以Post方式发送数据采用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));
下面采用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")));
................
?
轉載于:https://www.cnblogs.com/wdfrog/archive/2007/10/15/924833.html
總結
以上是生活随笔為你收集整理的以Post方式发送数据采用WebClient的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聊聊我对黑客技术的思考
- 下一篇: 今天20号!