10

How do i keep a connection alive in C#? I'm not doing it right. Am i suppose to create an HttpWebRequest obj and use it to go to any URLs i need? i dont see a way to visit a url other then the HttpWebRequest.Create static method.

How do i create a connection, keep it alive, browse multiple pages/media on the page and support proxys? (i hear proxy are easy and support is almost standard?) -edit- good answers. How do i request a 2nd url?

{
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://google.com");
WebRequestObject.KeepAlive = true;
//do stuff
WebRequestObject.Something("http://www.google.com/intl/en_ALL/images/logo.gif");
}
4

5 回答 5

20

Have you tried the HttpWebRequest.KeepAlive property? It sets the appropriate Keep-Alive HTTP header and does persist the connections. (Of course this must also be supported and enabled by the remote web server).

The HttpWebRequest.KeepAlive documentation on MSDN states that it is set to true by default for HTTP1.1 connections, so I suspect the server you're trying to contact does not allow connection persistence.

Proxy is used automatically and its settings are taken from your system (read Internet Explorer) settings. It is also possible to override the proxy settings via HttpWebRequest.Proxy property or by tweaking the application configuration file (see http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx).

于 2009-04-14T19:34:28.637 回答
9

Set HttpWebRequest.KeepAlive property True .NET will take care of the rest. It's just database connection pool. Works transparently.

You can create new connection freely .NET will figure it out that you are connecting an already connected server and will use it. Also depends on your Net.ServicePointManager.DefaultConnectionLimit number it will establish new connections (if you do multhithreading).

于 2009-04-14T19:34:29.167 回答
4

You can set the HttpWebRequest.KeepAlive property to true.

For the Proxies, there is a property also: HttpWebRequest.Proxy

于 2009-04-14T19:33:57.810 回答
2

当 HttpWebRequest.KeepAlive = true 不足以使其保持活力时,我遇到了类似的问题。只有在我设置 request.UnsafeAuthenticatedConnectionSharing = true 和 ServicePointManager.MaxServicePointIdleTime = 100000;//避免 0 或低值后连接才保持

于 2015-02-11T18:29:02.800 回答
1

如果您使用的是 Http 1.1,则不应使用 Keep-Alive,因为连接是隐式 Keep-Alive。

可以设置该HttpWebRequest.KeepAlive属性,但如果您发送 Http 1.1 请求,除非您将其设置为 Close,否则它实际上不会设置标头。

这是另一个包含更多信息的问题: HTTP/1.1 请求是否默认隐式保持活动?

于 2015-05-14T22:00:18.870 回答