title: HttpWebRequest Vs HttpClient
body: <p>I have a chunk of code that works using a <strong>HttpWebRequest</strong> and <strong>HttpWebResponse</strong> but I'd like to convert it to use <strong>HttpClient</strong> and <strong>HttpResponseMessage</strong>.</p>
  
  <p>This is the chunk of code that works...</p>
  
  <pre><code>HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceReq);
  
  request.Method = "POST";
  request.ContentType = "text/xml";
  string xml = @"&lt;?xml version=""1.0""?&gt;&lt;root&gt;&lt;login&gt;&lt;user&gt;flibble&lt;/user&gt;" + 
      @"&lt;pwd&gt;&lt;/pwd&gt;&lt;/login&gt;&lt;/root&gt;";
  request.ContentLength = xml.Length;
  using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
  {
      dataStream.Write(xml);
      dataStream.Close();
  }
  
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  </code></pre>
  
  <p>And this is the code that I'd like to replace it with, if only I could get it working.</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Validate the user credentials held as member variables
  /// &lt;/summary&gt;
  /// &lt;returns&gt;True if the user credentials are valid, else false&lt;/returns&gt;
  public bool ValidateUser()
  {
      bool valid = false;
  
      try
      {
          // Create the XML to be passed as the request
          XElement root = BuildRequestXML("LOGON");
  
          // Add the action to the service address
          Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");
  
  
          // Create the client for the request to be sent from
          using (HttpClient client = new HttpClient())
          {
              // Initalise a response object
              HttpResponseMessage response = null;
  
              // Create a content object for the request
              HttpContent content = HttpContentExtensions.
                  CreateDataContract&lt;XElement&gt;(root);
  
              // Make the request and retrieve the response
              response = client.Post(serviceReq, content);
  
              // Throw an exception if the response is not a 200 level response
              response.EnsureStatusIsSuccessful();
  
              // Retrieve the content of the response for processing
              response.Content.LoadIntoBuffer();
  
              // TODO: parse the response string for the required data
              XElement retElement = response.Content.ReadAsXElement();
          }
      }
      catch (Exception ex)
      {
          Log.WriteLine(Category.Serious, 
              "Unable to validate the Credentials", ex);
          valid = false;
          m_uid = string.Empty;
      }
  
      return valid;
  }
  </code></pre>
  
  <p>I think the problem is creating the content object and the XML isn't being attached correctly (maybe).</p>