0

I'm into uncharted territory - I have to create an httppost for the first time (xml). I've looked at plenty of examples but to be frank, its kinda confusing for a noob.

The function I'm currently working on is this:

    public string SubmitRequest(string postUrl, string contentType, string postValues)
    {
        var req = WebRequest.Create(postUrl);
        req.Method = "POST";
        req.ContentType = contentType;

        try
        {
            using (var reqStream = req.GetRequestStream())
            using (var writer = new StreamWriter(reqStream))
            {
                writer.WriteLine(postValues);
            }

            var resp = req.GetResponse();

            using (var respStream = resp.GetResponseStream())
            using (var reader = new StreamReader(respStream))
            {
                return reader.ReadToEnd().Trim();
            }

        }
        catch(WebException ex)
        {
            // do something here
        }

        return string.Empty;
    }

I suppose I have 2 questions:

Does the code seem correct in terms of correctly disposing/closing object? Is this the most effective way of writing my httppost given I'm using asp.net 4.0?

Thanks in advance

dotnetnoob
  • 10,783
  • 20
  • 57
  • 103

1 Answers1

1

Does the code seem correct in terms of correctly disposing/closing object?

No. You are closing the streams correctly but not the Reader and Writer objects. If any kind of buffering is going on you might lose data here.

The better way:

   using (var reqStream = req.GetRequestStream())       
   using (var writer = new StreamWriter(reqStream))
   {
      writer.WriteLine(postValues);
   }

And the same for the Reader. Note that this is nesting 2 using blocks, the indentation is slightly atypical but practical.

Is this the most effective way of writing my httppost given I'm using asp.net 4.0?

No.

  • use WebClient for less code. See here.
  • use async methods for more performance (a lot easier with C# 5)
Community
  • 1
  • 1
H H
  • 263,252
  • 30
  • 330
  • 514
  • Thanks for your answers Henk. I updated my answer, then saw your example - so thats good. I've looked at examples using WebClient, but cannot work out how to modify content type etc. – dotnetnoob May 04 '13 at 17:00
  • Follow the link in my answer. – H H May 04 '13 at 17:02