zoukankan      html  css  js  c++  java
  • 使用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;
            }

     

     

  • 相关阅读:
    使用xca生成SSL证书
    在 Apache error_log 中看到多个信息,提示 RSA server certificate CommonName (CN) 与服务器名不匹配(转)
    SSL/TLS 高强度加密: 常见问题解答
    JAVA 集合操作总结
    VUE 微信开发
    实战 ant design pro 中的坑
    Spring boot 配置 mybatis xml和动态SQL 分页配置
    VUE打包上线优化
    VUE中如何优雅的动态绑定长按事件
    用C自撸apache简易模块,搭建图片处理服务器。
  • 原文地址:https://www.cnblogs.com/default/p/2404277.html
Copyright © 2011-2022 走看看