【问题标题】:How to send KeepAlive header correctly in c#?如何在 C# 中正确发送 KeepAlive 标头?
【发布时间】:2012-03-23 03:26:33
【问题描述】:

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

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

  1. Keep a http connection alive in C#?
  2. C# - Connection: keep-alive Header is Not Being Sent During HttpWebRequest

如何正确发送 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 标头?

【问题讨论】:

  • 在http1.1中KeepAlive是默认的,不是吗?
  • 如果你使用 ServicePointManager.Expect100Continue = false;顺便说一句,有同样的问题。它是一个 .net 错误吗?

标签: c# httpwebrequest http-headers


【解决方案1】:

我在非常相似的代码和设置中遇到了同样的错误

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

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

【讨论】:

    【解决方案2】:

    使用 HTTP/1.1 时,Keep-Alive 默认开启。将 KeepAlive 设置为 false 可能会导致向服务器发送 Connection: Close 标头。

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 1970-01-01
      • 2019-04-29
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      相关资源
      最近更新 更多