• 必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]GetResponse。解决方法


    当在后台实现POST请求的时候,出现如下错误:

     必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]GetResponse。

    或者是如下错误:

    上述是因为由于我们使用的是代理服务器,那个还有一种原因不能忽略,就是如果目标网页的HTTP的版本号为1.0或之前的版本,而代理服务器的本版为1.1或以上。这么这是,代理服务器将不会转发我们的Post请求,并报错‍(417) Unkown

    再看wireshark的包信息,其中明确可以看出,协议的版本号为HTTP1.1。这样,我们基本上可以确定‍(417) Unkown的原因:

    握手失败,请求头域类型不匹配。

    解决方法:

    在配置文件加入

    <configuration>
    
    <system.net>
    
    <settings>
    
               <servicePointManager expect100Continue="false" />
    
    </settings>
    
    </system.net>
    
    </configuration>

    或者在请求前加入如下代码:

    System.Net.ServicePointManager.Expect100Continue = false;//默认是true,所以导致错误

    附加两种请求方法:

    方法一:

            public ActionResult b()
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                string Url = "http://xxx";
                string PostDataStr = string.Format("userName={0}&pwd={1}","a","b");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = PostDataStr.Length;
                
                StreamWriter write = new StreamWriter(request.GetRequestStream(),Encoding.ASCII);
                write.Write(PostDataStr);
                write.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding==null||encoding.Length<1) {
                    encoding = "UTF-8";
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.GetEncoding(encoding));
                string retstring = reader.ReadToEnd();
                return Content(retstring);
            }

    方法二:

            public async Task<ActionResult> a()
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                string postUrl = "http://xxx";
                var postContent = new FormUrlEncodedContent(new[]
                        {
                        new KeyValuePair<string, string>("userName", "a"),
                        new KeyValuePair<string, string>("pwd","b")
    
                        });
                var httpResponse = await new HttpClient().PostAsync(postUrl, postContent);
                var content = await httpResponse.Content.ReadAsStringAsync();
                return Content(content);
            }
  • 相关阅读:
    04_上架APPstore时候的宣传页尺寸
    03_iOS导航栏的正确隐藏方式
    02_iOS 沙盒及各个目录详解
    01_可变数组用copy修饰之后还是可变的的吗
    IOS label 设置行高
    Xcode11更改启动页设置方法
    swift 5.0 创建button方法
    ios 淘宝评论详情、朋友圈布局masony实现
    mysql安装问题
    重装win7时遇到点小问题
  • 原文地址:https://www.cnblogs.com/no27/p/5777272.html
Copyright © 2020-2023  润新知