如何在c#中正确发送KeepAlive标头

本文关键字:KeepAlive 标头 | 更新日期: 2023-09-27 18:26:50

我需要使用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

但是,我不能发送连接头。这是我的代码:

// 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属性不会出现。

此外,这些帖子对我不起作用:

  1. 在C#中保持http连接有效
  2. C#-连接:在HttpWebRequest期间未发送保持活动标头

如何正确发送连接标头?

更新

这添加了使用HTTP/1.0 保持活动

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标头?

如何在c#中正确发送KeepAlive标头

使用HTTP/1.1时,"保持活动"默认处于启用状态。将KeepAlive设置为false可能会导致向服务器发送Connection:Close标头。

我有同样的错误,代码非常相似,并且设置了

var sp = req.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
prop.SetValue(sp, (byte)0, null);

确实修复了它。你确定每次创建httpwebrequest时都会执行此代码吗?