1

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?

Can you give me a example? I can't find a solution in the internet.

Maybe you can explain me how i can do the next request with the Cookies from the first Page? :)

Hope for your answer.

Sorry for my bad english.

Here is my first Logintest :P

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 <NameValuePair> nvps = new ArrayList <NameValuePair>();
        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;
    }

}
Joni
  • 72
  • 1
  • 11

1 Answers1

0

you need to retrieve the Set-Cookie header from the response, store its value, and ask following requests with Cookie header and that value.

see this post for more explainer on cookies How are cookies passed in the HTTP protocol?

Community
  • 1
  • 1
Ran Koretzki
  • 464
  • 3
  • 15
  • I try to read the header... But i can't find cookies on the header so i can't save them – Joni Dec 18 '16 at 10:15