开发者

When does WebRequest.GetResponse() set Connection to "Keep-Alive" c#

开发者 https://www.devze.com 2023-03-13 07:13 出处:网络
I have the following function private byte[] Function(string url) { HttpWebRequest webRequest= (HttpWebRequest)WebRequest.Create(url);

I have the following function

private byte[] Function(string url)
{
    HttpWebRequest webRequest= (HttpWebRequest)WebRequest.Create(url);
    webRequest.AddRange(0, 200);
    webRequest.Method = "GET";
    webRequest.KeepAlive = true;

    byte[] buffer = new byte[200];
    using (var webResponse =  webRequest.GetResponse())
    using (Stream webResponseStreem = webResponse.GetResponseStream())
    {
        webResponseStreem.Read(buffer, 0, 200);
    }

    return buffer;
}

and I call it from different part of my application. Sometimes开发者_开发问答 the result that I get is not what I expect. I noticed that sometimes the call webRequest.GetResponse() sets webRequest.Connection to "Keep-Alive" and sometimes does not. What does it depend on?


I don't know what controls whether this header should be sent or not, but according to the documentation:

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.

So if you are using HTTP/1.1 it shouldn't matter whether the header is sent or not. If there is no Connection: close header the server should assume a persistent connection.

0

精彩评论

暂无评论...
验证码 换一张
取 消