使用HttpWebRequest post数据时要注意UrlEncode

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

clip_image001[6]

通过对比自己post__VIEWSTATE和服务器接收到的__VIEWSTATE的值(通过服务器的HttpApplicationBeginRequest事件可以取到Request里的值),发现__VIEWSTATE中的一个+号被替换成了空格。(由于ViewState太长,这个差异也是仔细观察了很久才看出来的)

造成这个错误的原因在于+号在url中是特殊字符,远程服务器在接受request的时候,把+转成了空格。同样的,如果想post的数据中有&%等等,也会被服务器转义,所以我们在post的数据的时候,需要先把数据UrlEncode一下。url  encodebs开发中本来是一个很常见的问题,但没想到还是在这里栽了跟头。

修改后的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";
                //dataUrlEncode
                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;
        }

 

 

原文地址:https://www.cnblogs.com/default/p/2404277.html