BumbleBee
BumbleBee

Reputation: 10799

how to keep connection live while using httpwebrequest?

I am using httpwebrequest and httpwebresponse to send request and get response respectively. For some reason my connection gets closed before the response is recieved.

Here is my code :

           WebRequest webRequest = WebRequest.Create (uri);
           webRequest.ContentType = "application/x-www-form-urlencoded";
           webRequest.Method = "POST";
           byte[] bytes = Encoding.ASCII.GetBytes (parameters);
           Stream os = null;
           try
           { // send the Post
              webRequest.ContentLength = bytes.Length;   //Count bytes to send
              os = webRequest.GetRequestStream();
              os.Write (bytes, 0, bytes.Length);         //Send it
           }
           catch (WebException ex)
           {
              MessageBox.Show ( ex.Message, "HttpPost: Request error", 
                 MessageBoxButtons.OK, MessageBoxIcon.Error );
           }
                        
           try
           { // get the response
              WebResponse webResponse = webRequest.GetResponse();
              if (webResponse == null) 
                 { return null; }
              StreamReader sr = new StreamReader (webResponse.GetResponseStream());
              return sr.ReadToEnd ().Trim ();
           }
           catch (WebException ex)
           {
              MessageBox.Show ( ex.Message, "HttpPost: Response error", 
                 MessageBoxButtons.OK, MessageBoxIcon.Error );
           }
           return null;
        }

Error :

alt text

Upvotes: 0

Views: 555

Answers (2)

feroze
feroze

Reputation: 7594

By default, if you are using HTTP/1.1 protocol, then the connection is assumed to be kept alive, unless the server decides to indicate otherwise (with a Connection: close header).

In your case, you are having a server refusing the request with a 500 error. You should investigate why that is happening. You shouldnt worry about the connection:close header at this point. Even if the server closes the connection, the client will handle that gracefully by opening a new connection the next time.

To summarize, the 500 response from the server is not due to the connection being closed. It is because the server does not like the request you sent.

Upvotes: 1

exiter2000
exiter2000

Reputation: 548

If it is session timeout error(I cannot see the error message), you should have configuration parameter like below in your web server or J2EE server.

Below is from tomcat web.xml

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

Upvotes: 0

Related Questions