title: Java Apache HTTP Client - Save Cookie for next request
body: <p>i'm starting with Programming Java and wan't to create a simple "Backend Crawler". For this i need a login function by Post thats not problem but how i can do the cookies wars saved and on the next request the Script don't need login again?</p>
  
  <p>Can you give me a example? I can't find a solution in the internet.</p>
  
  <p>Maybe you can explain me how i can do the next request with the Cookies from the first Page? :)</p>
  
  <p>Hope for your answer.</p>
  
  <p>Sorry for my bad english.</p>
  
  <p>Here is my first Logintest :P</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.List;
  import org.apache.http.HttpEntity;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.CloseableHttpResponse;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.methods.HttpGet;
  import org.apache.http.impl.client.CloseableHttpClient;
  import org.apache.http.impl.client.HttpClients;
  import org.apache.http.message.BasicNameValuePair;
  import org.apache.http.util.EntityUtils;
  import org.jsoup.Jsoup;
  import org.jsoup.nodes.Document;
  
  public class Login {
  
      public static String loginAndGetHTML() throws Exception {
          CloseableHttpClient httpclient = HttpClients.createDefault();
          String html;
  
          HttpPost HttpPost = new HttpPost("http://www.google.com");
          List &lt;NameValuePair&gt; nvps = new ArrayList &lt;NameValuePair&gt;();
          nvps.add(new BasicNameValuePair("username", "admin"));
          nvps.add(new BasicNameValuePair("password", "1234"));
          HttpPost.setEntity(new UrlEncodedFormEntity(nvps));
          HttpPost.addHeader("Referer", "http://tutorials.amazingcode.de/login/index.php");
          HttpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0");
          CloseableHttpResponse response = httpclient.execute(HttpPost);
  
          try {
              HttpEntity entity = response.getEntity();
              html = EntityUtils.toString(entity);
              EntityUtils.consume(entity);
          } finally {
              response.close();
          }
  
          if(html.contains("Falsche Nutzerdaten")) {
              throw new Exception("Login fehlgeschlagen");
          }
  
  
  
          return html;
      }
  
      public static String parseHTML(String html) throws Exception {
          Document doc = Jsoup.parse(html);
          String zahl = doc.getElementById("zahl").text();
          return zahl;
      }
  
  }
  </code></pre>