我需要使用HttpWebRequest发送这样的请求:
POST https://sap.site.com.mx/sap/bw/BEx?SAP-LANGUAGE=ES&PAGENO=1&CMD=PROCESS_VARIABLES&REQUEST_NO=0&CMD=PROCESS_VARIABLES&SUBCMD=VAR_SUBMIT&VARID= HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-MX,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
但是,我无法发送Connection标头。这是我的代码:
// request
HttpWebRequest request = CreateWebRequestObject(url);
request.CookieContainer = this.cc;
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2";
// headers
request.Headers.Add("Accept-Encoding", "gzip, deflate");
request.Headers.Add("Accept-Language", " es-MX,es;q=0.8,en-us;q=0.5,en;q=0.3");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.KeepAlive = true; // it does not work as expected
request.ServicePoint.Expect100Continue = false; // remove Expect header
// post
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
using (Stream stream = request.GetRequestStream())
stream.Write(buffer, 0, buffer.Length);
但是,当我在Fiddler中检查请求时,Connection属性不会出现。
此外,这些帖子对我不起作用:
如何正确发送Connection标头?
更新
使用HTTP / 1.0添加Keep-Alive
request.ProtocolVersion = HttpVersion.Version10;
//request.KeepAlive = true; // not necessary
将ProtocolVersion属性更改为HttpVersion.Version11时,Keep-Alive标头不会发送:
request.ProtocolVersion = HttpVersion.Version11;
request.KeepAlive = true;
如何使用Http / 1.1发送Keep-Alive标头?
答案 0 :(得分:3)
使用HTTP / 1.1时,默认情况下Keep-Alive处于启用状态。将KeepAlive设置为false可能会导致向服务器发送Connection:Close标头。
答案 1 :(得分:1)
我在代码非常相似的情况下遇到了同样的错误,并设置了
var sp = req.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
prop.SetValue(sp, (byte)0, null);
DID修复它。您确定每次创建httpwebrequest时都执行此代码吗?