您的位置:首页 > 理论基础 > 计算机网络

使用HttpWebRequest post数据时要注意UrlEncode

2016-08-24 12:52 501 查看
from  http://www.cnblogs.com/default/archive/2012/03/18/2404277.html

今天在用HttpWebRequest类向一个远程页面post数据时,遇到了一个怪问题,总是出现500的内部服务器错误,通过查看远程服务器的log,发现报的是“无效的视图状态”错误:



通过对比自己post的__VIEWSTATE和服务器接收到的__VIEWSTATE的值(通过服务器的HttpApplication的BeginRequest事件可以取到Request里的值),发现__VIEWSTATE中的一个+号被替换成了空格。(由于ViewState太长,这个差异也是仔细观察了很久才看出来的)
造成这个错误的原因在于+号在url中是特殊字符,远程服务器在接受request的时候,把+转成了空格。同样的,如果想post的数据中有&、%等等,也会被服务器转义,所以我们在post的数据的时候,需要先把数据UrlEncode一下。url  encode在bs开发中本来是一个很常见的问题,但没想到还是在这里栽了跟头。
修改后的post数据的示例代码如下,注意下面加粗的那句话:

        public HttpWebResponse GetResponse(string url)

        {

            var req = (HttpWebRequest)WebRequest.Create(url);

            req.CookieContainer = CookieContainer;

            if (Parameters.Count > 0)

            {

                req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                req.ContentType = "application/x-www-form-urlencoded";

                req.Method = "POST";

                //data要UrlEncode

                var postData = string.Join("&", Parameters.Select(

                                               p =>

                                               string.Format("{0}={1}", p.Key,

                                                             System.Web.HttpUtility.UrlEncode(p.Value, Encoding))).ToArray());

                var data = Encoding.GetBytes(postData);

                req.ContentLength = data.Length;

                using (var sw = req.GetRequestStream())

                {

                    sw.Write(data, 0, data.Length);

                }

            }

            req.Timeout = 40 * 1000;

            var response = (HttpWebResponse)req.GetResponse();

            return response;

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