Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send KeepAlive header correctly in c#?

I need to send a request like this using 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

However, I can not send Connection header. This is my code:

// 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);

But, when I check the request in Fiddler the Connection property does not appears.

In addition, these posts does not work for me:

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

How do I send Connection header correctly?

UPDATE

This add Keep-Alive using HTTP/1.0

request.ProtocolVersion = HttpVersion.Version10;
//request.KeepAlive = true;  // not necessary

When change ProtocolVersion property to HttpVersion.Version11, Keep-Alive header is not send:

request.ProtocolVersion = HttpVersion.Version11;
request.KeepAlive = true;

How can I send Keep-Alive header using Http/1.1?

like image 270
auraham Avatar asked Oct 09 '22 12:10

auraham


1 Answers

When using HTTP/1.1, Keep-Alive is on by default.Setting KeepAlive to false may result in sending a Connection: Close header to the server.

like image 152
Dalamar81 Avatar answered Oct 12 '22 10:10

Dalamar81