Try ... Catch and HTTP Requests
<p>My program makes web requests, but sometimes I will get an exception saying the server closed the connection. When this happens I need to re-open a connection.</p>

<p>Should I put the code in a try ... catch? If the connection is closed in the try, reopen it in the catch? But my issue would be, what if the servers closes the connection opened in the catch?</p>

<p>Here is my code at the moment.</p>

<pre><code>public String postRequest(String pD, String url)
    {
        String postData = pD;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        byte[] buffer = Encoding.ASCII.GetBytes(postData);

        /** Set the headers **/
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = buffer.Length;
        request.ServicePoint.Expect100Continue = false;
        request.Method = "post";

        Stream PostData = request.GetRequestStream();
        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        StreamReader read = new StreamReader(responseStream);

        String line; String source = "";
        while ((line = read.ReadLine()) != null) source += line;
        return source;
     }
</code></pre>
