tags:

views:

40

answers:

1

I would like to create 2 HTTP requests on the same connection (HTTP persistent connection).

I'm using HttpWebRequest:

        WebRequest request = HttpWebRequest.Create("http://localhost:14890/Service1/3");
        WebResponse response = request.GetResponse();

        byte[] buffer = new byte[1024];
        int x = response.GetResponseStream().Read(buffer, 0, 1024);
        string str = System.Text.ASCIIEncoding.ASCII.GetString(buffer);

I think if I use request again it will create a whole new HTTP connection which I don't want to do.

Is there another class I can use isntead or is there something I'm missing?

I'm also not sure how the WebClient class works with respect to persistent connections.

+1  A: 

Set the KeepAlive property.

For example:

string str;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:14890/Service1/3");
request.KeepAlive = true;
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream, Encoding.ASCII)) {
    str = reader.ReadToEnd();
}
SLaks
And how do I make the second request within that same connection?
wcf guru needed
The .Net framework should automatically re-use the connection.
SLaks
so the connection is like a static property of HttpWebRequest, I kind of need control of when to have persistent connections and when not to via multiple threads all using different HttpWebRequests.
wcf guru needed
It seems like there something missing for control here. What if I want to maintain 2 HTTP connections.
wcf guru needed
@wcf guru needed, no, it's not static. The connection is handled by the ServicePoint class
Thomas Levesque
@wcf: You need to maintain multiple `ServicePoint` instances.
SLaks
ServicePoint is a read only property of the HttpWebRequest though
wcf guru needed