c# HttpWebRequest and HttpWebResponse generic stuff

706 views Asked by At

I am playing around with an app using HttpWebRequest to dialog with a web server.

I followed standard instructions I found on the web to build my request function that I tried to make as generic as possible (I try to get a unique method regardless of the method: PUT, POST, DELETE, REPORT, ...)

When I submit a "REPORT" request, I get two access logs on my server:

1) I get response 401 after following line is launched in debugger

reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);

2) I get response 207 (multi-get, which is what I expect) after passing the line calling Request.GetResponse();

Actually, it seems to be the Request.GetRequestStream() line that is querying the server the first time, but the request is only committed once passing the reqStream.Write(...) line...

Same for PUT and DELETE, the Request.GetRequestStream() again generates a 401 access log on my server whereas the Request.GetResponse(); returns code 204.

I don't understand why for a unique request I have two server access logs, especially one that seems to be doing nothing as it always returns code 401... Could anybody explain what is going on? Is it a flaw in my code or a bad design due to my attempt to get a generic code for multiple methods?

Here is my full code:

public static HttpWebResponse getHttpWebRequest(string url, string usrname, string pwd, string method, string contentType, 
                                       string[] headers, string body) {
  // Variables.
  HttpWebRequest Request;
  HttpWebResponse Response;
  //
  string strSrcURI = url.Trim();
  string strBody = body.Trim();
  try {
    // Create the HttpWebRequest object.
    Request = (HttpWebRequest)HttpWebRequest.Create(strSrcURI);

    // Add the network credentials to the request.
    Request.Credentials = new NetworkCredential(usrname.Trim(), pwd);

    // Specify the method.
    Request.Method = method.Trim();

    // request headers
    foreach (string s in headers) {
      Request.Headers.Add(s);
    }

    // Set the content type header.
    Request.ContentType = contentType.Trim();

    // set the body of the request...
    Request.ContentLength = body.Length;
    using (Stream reqStream = Request.GetRequestStream()) {
      // Write the string to the destination as a text file.
      reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);
      reqStream.Close();
    }

    // Send the method request and get the response from the server.
    Response = (HttpWebResponse)Request.GetResponse();

    // return the response to be handled by calling method...
    return Response;
  }
  catch (Exception e) {
    throw new Exception("Web API error: " + e.Message, e);
  }
0

There are 0 answers