简体   繁体   中英

Closing response from HTTPS POST request with exception

As it is shown in my previous question about sending HTTPS POST request in multithreading c# can't write POST data to https request , I'd like to be sure that responses are closed if exception is caught during HTTPS POST request. Here is the code snippet:

public void request_3()
{
     byte[] byteArray3 = Encoding.ASCII.GetBytes(post_data_final3);
     Console.WriteLine(Thread.CurrentThread.Name + " " + "request_2 started");
     HttpWebRequest request3 = (HttpWebRequest)WebRequest.Create(site_URI);
     WebHeaderCollection NewHeaders3 = request3.Headers;
     request3.CookieContainer = new CookieContainer();
     request3.Method = "POST";
     //headers info
     request3.Timeout = 60000;
     request3.ContentLength = byteArray3.Length;
     try
     {
         using (Stream os3 = request3.GetRequestStream())
         {
             os3.Write(byteArray3, 0, byteArray3.Length);
         }
     }
     catch (WebException ex33)
     {
         Console.WriteLine(ex33);
         Console.WriteLine(ex33.Status);
     }
     try
     {
         HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse();
         //response handling
         response3.Close();
     }
     catch (WebException wex3)
     {
         Console.WriteLine(wex3);
         Console.WriteLine(wex3.Status);
     }
}

The question here is what if I get an exception during the response so the following code will be used:

catch (WebException wex3)
         {
             Console.WriteLine(wex3);
             Console.WriteLine(wex3.Status);
         }

Shall I close the response within "Catch" block like

response3.Close();

Or

wex3.Response.Close();

To prevent 3rd response freezing if 2 responses got exception? Or does it mean that if I got an exception response is automatically closed? Thanks!

Use finally to ensure the response is closed regardless of what happens in the try/catch:

HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse();
try
{
    // response handling
}
catch (WebException wex3)
{
    Console.WriteLine(wex3);
    Console.WriteLine(wex3.Status);
}
finally
{
     response3.Close();
}

Or, better still, HttpWebResponse implements IDisposable , meaning you can let it take care of itself:

using (HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse())
{
    try
    {
        // response handling
    }
    catch
    {
        Console.WriteLine(wex3);
        Console.WriteLine(wex3.Status);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM