title: Login HttpRequest with credentials using c# (got working javascript code)
body: <p>For the past 5 hours I've been trying to get JSON data from an API that requires login using .net C#. 
  Every combination I try results in "error 401 - unauthorized".
  I have a working example in Javascript, maybe this would help.</p>
  
  <pre><code>       function signin(){
          username = $('#inputUsername').val();
          pass = $('#inputPassword').val();
          if(pass.length &gt; 0 &amp;&amp; username.length &gt; 0){
              //Build post request
              $.post( source+"/login", {username: username, password:pass}, function( data, textStatus, jqxhr ) {
                  $("header div h4#header_username").html(username);
                  token = data.auth;
                  $('#main-content').show()
                  $('#form-signin').hide()
                  populateVehicles();
              });
          }
      }
  </code></pre>
  
  <p>On c# I've tried many code combinations including:</p>
  
  <pre><code>NetworkCredential netCredential = new NetworkCredential("USERNAME", "PASSWORD");
  
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
          request.Credentials = netCredential;
          request.Method = "POST";
          String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("USERNAME" + ":" + "PASSWORD"));
          //request.PreAuthenticate = false;
          //request.Proxy.Credentials = CredentialCache.DefaultCredentials;
          //request.UseDefaultCredentials = true;
  
          //string base64Credentials = GetEncodedCredentials();
          //request.Headers.Add("Authorization", "Basic " + base64Credentials);
          try
          {
              WebResponse response = request.GetResponse();
              using (Stream responseStream = response.GetResponseStream())
              {
                  StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                  return reader.ReadToEnd();
              }
          }
          catch (WebException ex)
          {
              WebResponse errorResponse = ex.Response;
              using (Stream responseStream = errorResponse.GetResponseStream())
              {
                  StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
                  String errorText = reader.ReadToEnd();
                  // log errorText
              }
              throw;
          }
      }
  </code></pre>
  
  <p>Some of the code has "//" because I've tried various variations.</p>
  
  <p>I'm clueless.</p>
  
  <p>Thanks in advance!</p>