以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号!