2012-03-05 79 views
5

我需要使用的HttpWebRequest發送這樣的請求:如何在C#中正確發送KeepAlive頭文件?

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. Keep a http connection alive in C#?
  2. C# - Connection: keep-alive Header is Not Being Sent During HttpWebRequest

如何正確地發送連接頭?

UPDATE

這個附加保活使用HTTP/1.0

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

當變化ProtocolVersion屬性HttpVersion.Version11,保持活動頭沒有被髮送:

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

如何使用Http/1.1發送Keep-Alive頭文件?

+0

在http1.1中KeepAlive是默認的,不是? – 2012-03-05 18:02:59

+0

如果您使用ServicePointManager.Expect100Continue = false;順便說一下,有同樣的問題。它是一個.net錯誤嗎? – 2012-03-10 17:29:59

回答

1

我有非常相似的代碼相同的錯誤,並設置

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

DID解決它。你確定每次創建httpwebrequest時都確實執行了這段代碼嗎?

3

使用HTTP/1.1時,Keep-Alive默認爲打開。將KeepAlive設置爲false可能會導致向服務器發送Connection:Close標頭。