title: c# httpwebrequest for basic authentication
body: <p>I've been trying to use a username, password and access key to authenticate on a server, so that I could use its API. I used to following code:</p>
  
  <pre><code>        string encoded = Convert.ToBase64String(Encoding.Default.GetBytes("myusername:mypass"));      
          string api = "blahblahblahblabh";
          string auth_string = "Basic " + encoded;
          string _post_string = "username=myusername&amp;password=mypass&amp;grant_type=password";
          HttpWebRequest request = WebRequest.Create(https_website) as HttpWebRequest;
          request.Accept = "application/xml";
          request.Method = "POST";            
          request.ContentType = "application/x-www-forms-urlencoded";
          request.ContentLength = _post_string.Length;
          CookieContainer cookies = new CookieContainer();
          request.CookieContainer = cookies;
  
          request.Headers["Authorization"] = auth_string;
          request.Headers["api-key"] = api;
          request.ServerCertificateValidationCallback += (sender1, certificate, chain, sslPolicyErrors) =&gt; { return true; };
          StreamWriter writer = new StreamWriter(request.GetRequestStream());
          writer.Write(_post_string);
          writer.Close();
  
          HttpWebResponse response = request.GetResponse() as HttpWebResponse;
          StreamReader reader = new StreamReader(response.GetResponseStream());
  
          string xml_response = reader.ReadToEnd();
          reader.Close();
  </code></pre>
  
  <p>So I sent a POST request with the username/password and access_key and tried to receive a response. I always get "The remote server returned an error: (404) Not Found". If I add more to the string of the 1st line, for example if instead of "myusername:mypass" I use "myusername:mypass:password" I get an error 401 (Unauthorized). I don't understand why this is happening...</p>