title: Android: log into website and preserve session/cookie using DefaultHttpClient
body: <p>I've been through different tutorials and this website, but couldn't find a proper solution. On the other hand, I've seen apps logging into websites and requesting further information, so I'm sure there's a way to get this working, but maybe my approach is all wrong.</p>
  
  <p>Here's what I'm trying to do: I want to log into a website that needs user authentication and then read and parse websites that are only accessible if the user is logged in.
  The problem: after POSTing the credentials to the website, I receive a cookie which doesn't seem to be preserved in my HttpClient, even though the docs suggest that exactly that should happen.</p>
  
  <p>Here's some of my code:</p>
  
  <pre><code>DefaultHttpClient httpclient = new DefaultHttpClient();
  HttpPost httpost = new HttpPost(LOGIN_URL);
  
  List&lt;NameValuePair&gt; nvps = new ArrayList&lt;NameValuePair&gt;();
  nvps.add(new BasicNameValuePair(USER_FIELD, login));
  nvps.add(new BasicNameValuePair(PASS_FIELD, pw));
  nvps.add(new BasicNameValuePair(REMEMBERME, "on"));
  
  httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
  
  HttpResponse response = httpclient.execute(httpost);
  HttpEntity entity = response.getEntity();
  
  if (entity != null) {
    entity.consumeContent();
  }
  
  List&lt;Cookie&gt; cookies = httpclient.getCookieStore().getCookies();
  </code></pre>
  
  <p>When I output the contents of "cookies", everything seems fine (I receive a session):</p>
  
  <p><code>- [version: 0][name: ASP.NET_SessionId][value: xxx][domain: xxx][path: /][expiry: null]</code></p>
  
  <p>As I understood, the cookie/session will be preserved and used in my HttpClient as long as I don't close it.</p>
  
  <p>When reading the next page (which is restricted), using this code:</p>
  
  <pre><code>HttpGet httpget2 = new HttpGet(RESTRICTED_URL);
  response = httpclient.execute(httpget2);
  entity = response.getEntity();
  InputStream data = entity.getContent();
  // data will be parsed here
  if (entity != null) {
      entity.consumeContent();
  }
  // connection will be closed afterwards
  </code></pre>
  
  <p>If I output the response of the GET-request (using <code>response.getStatusLine()</code>) I get a "200 OK" message, but parsing the site that is returned shows, that the login is lost (I only retrieve a login form).</p>
  
  <p>Any help is appreciated.</p>