首页 > 解决方案 > 无法为不写入数据的操作设置 Content-Length 或 Chunked Encoding 我该怎么办?

问题描述

我尝试访问网站上的特定页面并将其从信息中提取出来。我确实GET请求了主页,我得到了响应状态代码 ==OK 然后我对GET包含Json我要检索的页面的另一个请求)和响应状态代码 == OK。

现在我想检索信息,所以我确实得到了对资源的请求(最后一页加载的另一个 URL)并且我在这一行得到了错误:

HttpWebResponse oHttpResponseIndicesApiUrl = (HttpWebResponse)oHttpRequestIndicesApiUrl.GetResponse();

“不能为不写入数据的操作设置 Content-Length 或 Chunked Encoding”

我设置了所有标题就像 chrome Inspect -> Network Tab -> 选择我想要的 URL 中的获取请求一样(我可以看到获取请求标题)

这是我运行的代码:

HttpWebRequest oHttpRequestIndicesApiUrl = (HttpWebRequest)WebRequest.Create(sIndicesApiURL);
            LOG.DebugFormat("{0}:calculateIndexSecurityWeights(), Create get request to '{0}'", Name, sIndicesApiURL);
            oHttpRequestIndicesApiUrl.CookieContainer = new CookieContainer();
            foreach (Cookie oCookie in oHttpResponseIndicesParmsUrl.Cookies)
            {
                oHttpRequestIndicesApiUrl.CookieContainer.Add(oCookie);
            }
            oHttpRequestIndicesApiUrl.AllowAutoRedirect = false;
            oHttpRequestIndicesApiUrl.Accept = ("application/json, text/plain, */*");
            oHttpRequestIndicesApiUrl.Headers.Add("accept-encoding", "gzip, deflate, br");
            oHttpRequestIndicesApiUrl.Headers.Add("accept-language", "he-IL");
            oHttpRequestIndicesApiUrl.KeepAlive = true;
            oHttpRequestIndicesApiUrl.ContentLength = 120;
            oHttpRequestIndicesApiUrl.ContentType = "application/json;charset=UTF-8";
            oHttpRequestIndicesApiUrl.Host = "api.tase.co.il";
            oHttpRequestIndicesApiUrl.Headers.Add("origin", "https://www.tase.co.il");
            oHttpRequestIndicesApiUrl.Referer = sIndicesParamsURL;
            oHttpRequestIndicesApiUrl.Headers.Add("sec-fetch-mode", "cors");
            oHttpRequestIndicesApiUrl.Headers.Add("sec-fetch-site", "same-site");
            oHttpRequestIndicesApiUrl.Headers.Add("upgrade-insecure-requests", "1");
            oHttpRequestIndicesApiUrl.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36";

            LOG.DebugFormat("{0}:calculateIndexSecurityWeights(), Set headers to '{1}'", Name, sIndicesApiURL);
            HttpWebResponse oHttpResponseIndicesApiUrl = (HttpWebResponse)oHttpRequestIndicesApiUrl.GetResponse();
            if (oHttpResponseIndicesApiUrl.StatusCode != HttpStatusCode.OK)
            {
                // response failed 
                throw new ApplicationException(string.Format("get response from url '{0}' failed, Status Code: '{1}', Status Description '{2}'", sIndicesApiURL, oHttpResponseIndicesApiUrl.StatusCode, oHttpResponseIndicesApiUrl.StatusDescription));
            }

我不明白为什么会这样?

标签: c#httpwebrequesthttpwebresponse

解决方案


推荐阅读