C#中遇到一个POST传递raw参数的问题[操作超时]

发布于 / 代码分享 / 358 条评论

具体的参数如下


                        var data = "{\"taskId\": \"" + taskId + "\", \"page\": \"" + i + "\", \"pageNum\": \"" + pagesize + "\"}";
                        var ret = WebRequestHelper.PostHttp(_url, data, "application/json");

然后遇到一个很诡异的事情,一直操作超时,然后请教了我们的技术大佬

尝试了一波之后还是无效,最后百度了一阵子,我们的开发小伙伴找到了一个属性设置
ProtocolVersion

官方解释:HttpWebRequest 类仅支持 HTTP 的1.0 和1.1 版本。 将 ProtocolVersion 设置为其他版本会引发异常。(说了跟没说一样)
备注:若要设置当前请求的 HTTP 版本,请使用 HttpVersion 类的 Version10 和 Version11 字段。

最后在代码里加上了刚才那一段


        public static string PostHttp(string url, string body, string contentType, Dictionary headers = null)
        {
            string content = string.Empty;
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;
            StreamReader sr = null;
            try
            {
                if (url.ToLower().StartsWith("https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                }

                webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.ProtocolVersion = HttpVersion.Version10;
                webRequest.ContentType = contentType;
                webRequest.Method = "POST";
                webRequest.Timeout = 20000;
                //header
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        webRequest.Headers.Add(header.Key, header.Value);
                    }
                }

                byte[] btbodys = Encoding.UTF8.GetBytes(body);
                webRequest.ContentLength = btbodys.Length;
                webRequest.GetRequestStream().Write(btbodys, 0, btbodys.Length);

                webResponse = (HttpWebResponse)webRequest.GetResponse();
                sr = new StreamReader(webResponse.GetResponseStream());
                content = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sr != null) sr.Close();
                if (webResponse != null) webResponse.Close();
                if (webRequest != null) webRequest.Abort();
            }
            return content;
        }

测试成功!问题解决~~~

转载原创文章请注明,转载自: 大鱼的博客 » C#中遇到一个POST传递raw参数的问题[操作超时]
没有评论权限