title: How to Authenticate Against Website Using Apache HttpClient 4.2.1 or >?
body: <p>I'm new to http programming and I'm attempting to authenticate against a website that doesn't use an API and I'm having some trouble. I found a few other questions that seemed to be similar to mine, but none had an answer that worked for me.</p>
  
  <p>I've tried several different approaches but haven't found one that works yet. Actually, I had it work for me once, but didn't check in that code (I know - what was I thinking?). I haven't been able to get back to that working version again. Here are a few things that I've tried so far:</p>
  
  <pre><code>    HttpClient client = new DefaultHttpClient(); //or any method to get a client instance, with a 'threadsafe' connection manager or otherwise
      Credentials credentials = new UsernamePasswordCredentials(userName, passwd);
      ((DefaultHttpClient) client).getCredentialsProvider()
                                  .setCredentials(AuthScope.ANY, credentials);
  
  // website is defined as my target website &amp; this constitutes the valid login URL
      HttpPost post = new HttpPost(https + website + "/login");
      HttpEntity entity = new StringEntity("Username="+ userName +"&amp;Password="+ passwd);
      post.setEntity(entity);
  
      HttpResponse response = client.execute(post);
      EntityUtils.consume(entity);
      entity = response.getEntity();
      EntityUtils.consume(entity);
  
  // the protected part of the site is over http after authentication succeeds
      HttpGet get = new HttpGet(http + website +"/protected");
      response = client.execute(get);
      entity = response.getEntity();
      String content = EntityUtils.toString(entity);
  </code></pre>
  
  <p>At this point the 'entity' I get back from the website is "error":"Unauthorized Access." </p>
  
  <p>You'll notice that I have a 'Credentials' instance being passed to the HttpClient and I'm also putting the user name &amp; password in the HttpPost entity. I tried each of these approaches separately and they both returned the "error":"Unauthorized Access." result.</p>
  
  <p>I've tried the DefaultHttpClient, which uses a single thread connection manager, as well as 'ThreadSafeClientConnManager' and neither worked. </p>