0

I have this update function that POSTs JSON data to a url and I got most of the POST parts from stack overflow questions. But I'm having a little trouble understanding what part of it means.

Here's my code:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
      GridViewRow row = GridView1.Rows[e.RowIndex];
      string startTime = row.Cells[1].Text;
      string endTime = row.Cells[2].Text;
      string furnace = row.Cells[4].Text;
      long ID = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
      CascadingDropDown cddSubsystem = (CascadingDropDown) row.FindControl("cddSubsystem");
      CascadingDropDown cddReason = (CascadingDropDown) row.FindControl("cddReason");
      DropDownList ddForcedSched = (DropDownList) row.FindControl("ddEditForcedSched");
      TextBox txtComments = (TextBox) row.FindControl("txtEditOperatorComments");

      // cascading dropdowns have the selected value formatted like this ReasonCode:::ReasonName
      string[] reason = cddReason.SelectedValue.Split(new string[] {":::"}, StringSplitOptions.None);
      string[] subsystem = cddSubsystem.SelectedValue.Split(new string[] {":::"}, StringSplitOptions.None);

      // get the machine code
      string machine = "";
      foreach (SorEvent evt in _events)
          if (evt.Id == ID)
              machine = evt.MachineCode;

      // create SorEvent object to post
      SorEvent updateSorEvent = new SorEvent()
      {
          Id = ID,
          Furnace = furnace,
          StartTime = Convert.ToDateTime(startTime),
          EndTime = endTime != " " ? Convert.ToDateTime(endTime) : (DateTime?) null,
          MachineCode = machine,
          ReasonCode = reason[0],
          SubsystemCode = subsystem[0],
          ForceScheduleFlag = ddForcedSched.SelectedValue,
          OperatorComments = txtComments.Text,
      };

      // POST to url
      string url = @"http://cannot.divulge:3020/this/URL/";
      HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
      req.Accept = "application/json";
      req.ContentType = "application/json";
      req.Method = "POST";

      // build a string with the params and encode it
      string data = JsonConvert.SerializeObject(updateSorEvent);
      ASCIIEncoding encoding = new ASCIIEncoding();
      Byte[] bytes = encoding.GetBytes(data);

      // send the request
      using (Stream post = req.GetRequestStream())
      {
          post.Write(bytes, 0, bytes.Length);
      }

      var response = req.GetResponse();
      var stream = response.GetResponseStream();
      var sr = new StreamReader(stream);
      var content = sr.ReadToEnd();

      // return to non-edit state
      GridView1.EditIndex = -1;
      SetData();
}

I understand most of the POSTing functionality, but I'm confused about the following:

var response = req.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

I know that the response variable gets the response from the request that I defined above and then I'm creating a stream from the response and reading it and setting it to a variable called content.

Is the purpose of that segment of code to show that the url POST was successful?

I know that

post.Write(bytes, 0, bytes.length);

is doing the actual post, so the code after it must be for confirmation.

This is where I got my code: POSTing JSON to URL via WebClient in C#

Community
  • 1
  • 1
user
  • 715
  • 4
  • 13
  • 32

2 Answers2

1

You are sort of right because after reading the response from your POST you are just ignoring it although that probably isn't a great idea. The response may contain warning or error messages and you are simply ignoring it - heading for trouble!

So in basic terms you are...

  1. Post some data to a URL
  2. Get the response data
  3. Throw the response data away
  4. Carry on in blissful ignorance

Maybe you should...

  1. Post some data to a URL
  2. Get the response data
  3. Check you get a SUCCESS response (200 etc) and content is sensible
  4. Carry on in confidence!
Belogix
  • 8,129
  • 1
  • 27
  • 32
  • When I debugged it, I was getting an error 404 and at the time I wasn't really sure what was going on and I commented that code out. So I went back and looked at the code and realized that I know what the rest of it is doing, I just didn't know what that part was doing. Thanks for the answer! – user Dec 19 '13 at 15:54
1

This code is quite self-explanatory, and you seem to understand it well.

Except that receiving a response doesn't mean everything is OK. Technically, the thing indicating it went well should be the response status code.

200 would indicate everything went well, 404 that the page was not found, 5XX would indicate a server error and so on. More info on Wikipedia

Note that it also depends on the developer of the service you're posting too and how he handles the success/failed requests : he could for example always return a response object (json/xml/...) with its own status code indicating all went well or not (ex: error status if wrong data was posted) and in that case you would get a status code of 200 for the request itself cause it actually worked, but you would need to parse the response content to know if everything indeed went well. Other developers might use the HTTP response status code to indicate success or fail of the process, including software errors.

I think this last one is the best practice. As a matter of information, the status code is used for example by jQuery to switch between successand error handlers when doing an AJAX request. That's why I think it's better to handle errors that way...

Laurent S.
  • 6,816
  • 2
  • 28
  • 40
  • That makes sense, that's why it returned an error 404 while debugging because the url I was using was incorrect. So it's basically just returning status codes (custom or otherwise). Thanks for the answer! – user Dec 19 '13 at 15:52