您的位置:首页 > 其它

以Post方式发送数据采用WebClient

2016-05-13 15:23 204 查看
通过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")));

................
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: