title: HttpClient 4.x how to use cookies?
body: <p>I'm trying to use the cookies I get in a response to my post method using <code>HttpClient 4.0.3</code>;</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public void generateRequest()
  {
      DefaultHttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://mysite.com/login");
      httpclient.getParams().setParameter("http.useragent", "Custom Browser");
      httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
              HttpVersion.HTTP_1_1);
      httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
              CookiePolicy.BROWSER_COMPATIBILITY);
  
      CookieStore cookieStore = new BasicCookieStore();
      HttpContext localContext = new BasicHttpContext();
      localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
  
      try
      {
          LOG.info("Status Code: sending");
          List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2);
          nameValuePairs.add(new BasicNameValuePair("email", "john%40gmail.com"));
          nameValuePairs.add(new BasicNameValuePair("password", "mypassword"));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          httppost.setHeader("ContentType", "application/x-www-form-urlencoded");
          HttpResponse response = httpclient.execute(httppost, localContext);
          HttpEntity entity = response.getEntity();
          if (entity != null)
          {
              entity.consumeContent();
          }
          iterateCookies(httpclient);
  
      }
      catch (ClientProtocolException e)
      {
          LOG.error("ClientProtocolException", e);
      }
      catch (IOException e)
      {
          LOG.error("IOException", e);
      }
  }
  
  private void iterateCookies(DefaultHttpClient httpclient)
  {
      List&lt;Cookie&gt; cookies = httpclient.getCookieStore().getCookies();
      if (cookies.isEmpty())
      {
          System.out.println("No cookies");
      }
      else
      {
          for (Cookie c : cookies)
          {
              System.out.println("-" + c.toString());
          }
      }
  }
  </code></pre>
  
  <p>But I keep getting the <code>No cookies</code> logged out even though when I use web-sniffer.net, I get this response:</p>
  
  <pre><code>Status:            HTTP/1.1 302 Found
  Cache-Control:     private, no-store    
  Content-Type:      text/html; charset=utf-8 
  Location:          http://www.mysite.com/loginok.html   
  Server:            Microsoft-IIS/7.0    
  X-AspNet-Version:  2.0.50727    
  Set-Cookie:        USER=DDA5FF4E1C30661EC61CFA; domain=.mysite.com; expires=Tue, 08-Jan-2013     18:39:53 GMT; path=/   
  Set-Cookie:        LOGIN=D6CC13A23DCF56AF81CFAF; domain=.mysite.com; path=/ Date: Mon, 09     Jan 2012 18:39:53 GMT 
  Connection:        close    
  Content-Length:    165
  </code></pre>
  
  <p>All the examples I've found online that make any sort of sense refer to HttpClient 3.x where you can set the <code>CookiePolicy</code> to <code>IGNORE</code> and handle the <code>Set-Cookie</code> header manually. I can't understand why this is so difficult in <code>4.x</code>. I need access to the <code>USER</code> hash for a number of reasons. Can anyone please tell me how in the hell I can get access to it?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I have found the following <code>C#</code> code which does the same thing and works correctly. </p>
  
  <pre><code>private static string TryGetCookie(string user, string pass, string baseurl)
      {
          string body = string.Format("email={0}&amp;password={1}", user, pass);
          byte[] bodyData = StringUtils.StringToASCIIBytes(body);
  
          HttpWebRequest req = WebRequest.Create(baseurl) as HttpWebRequest;
  
          if (null != req.Proxy)
          {
              req.Proxy.Credentials = CredentialCache.DefaultCredentials;
          }
  
          req.AllowAutoRedirect = false;
          req.Method = "Post";
          req.ContentType = "application/x-www-form-urlencoded";
          req.ContentLength = bodyData.Length;
  
          using (Stream reqBody = req.GetRequestStream())
          {
              reqBody.Write(bodyData, 0, bodyData.Length);
              reqBody.Close();
          }
  
          HttpWebResponse resp1 = req.GetResponse() as HttpWebResponse;
  
          string cookie = resp1.Headers["Set-Cookie"];
  
          if( string.IsNullOrEmpty(cookie))
          {
              if (0 &lt; resp1.ContentLength)
              {
                  // it's probably not an event day, and the server is returning a singlecharacter
                  StreamReader stringReader = new StreamReader(resp1.GetResponseStream());
  
                  return stringReader.ReadToEnd();
              }
  
              return null;
          }
  
          return ParseCookie(cookie);
      }
  </code></pre>
  
  <p>I believe my java code is not forming the post request correctly because when I use a URLConnection and print the request header from web-sniffer.net below: </p>
  
  <pre><code>POST /reg/login HTTP/1.1[CRLF]
  Host: live-timing.formula1.com[CRLF]
  Connection: close[CRLF]
  User-Agent: Web-sniffer/1.0.37 (+http://web-sniffer.net/)[CRLF]
  Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
  Cache-Control: no-cache[CRLF]
  Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
  Referer: http://web-sniffer.net/[CRLF]
  Content-type: application/x-www-form-urlencoded[CRLF]
  Content-length: 53[CRLF]
  [CRLF]
  email=john%40gmail.com&amp;password=mypassword
  </code></pre>
  
  <p>I get a response from the server that contains the <code>set-cookies</code> header. Is my java code not generating the request the same as web-sniffer.net?</p>
  
  <p>I have seen a post method generated using this code:</p>
  
  <pre><code>PostMethod authPost = new PostMethod("http://localhost:8000/webTest/j_security_check");
  // authPost.setFollowRedirects(false);
  NameValuePair[] data = {
  new NameValuePair("email", "john%40gmail.com"),
  new NameValuePair("password", "mypassword")
  };
  authPost.setRequestBody(data);
  status = client.executeMethod(authPost); 
  </code></pre>
  
  <p>The main difference here being that the <code>NameValuePair</code> data is set in the request body rather than set as the entity. Does this make a difference? Would this produce the correct request header?</p>