Search code examples
javafacebookcookiesjsoup

Login to Facebook with Jsoup and proper cookies


I am currently trying to automatically scrap my own home page and possibly other pages that I have access to when logged in to facebook. However I can't seem to be "logged" in after using the code below and setting the cookie.

Connection.Response res = Jsoup.connect("http://www.facebook.com/login.php?login_attempt=1")
            .data("email", "#####", "pass", "#####").userAgent("Mozilla")
            .method(Method.POST)
            .execute();

    Map<String, String> cookies = res.cookies();

        try{
            Document doc2 = Jsoup.connect("https://www.facebook.com/")
                .cookies(cookies).post();
            System.out.println(doc2.text());
            }
            catch(Exception e){
                e.printStackTrace();
            }

When I do this it will just send me back the facebook home page as though I were not logged in. When I try my own about page I get

HTTP error fetching URL. Status=404

Am I doing something wrong here? Are there other fields I need to set? I found another post that said other fields need to be set but I haven't the slightest clue how to find this information. The post can be found here Login Facebook via Jsoup

Any advice would be helpful. Thank you in advanced.


Solution

  • You can see a example here: How to Login on Facebook w/ Jsoup

    public static void main(String[] args) {
    
        Response req;
        try {
            String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36";
    
            req = Jsoup.connect("https://m.facebook.com/login/async/?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100")
                .userAgent(userAgent)
                .method(Method.POST).data("email", "YOUR_EMAIL").data("pass", "YOUR_PASSWORD")
                .followRedirects(true).execute();
    
            Document d = Jsoup.connect("https://m.facebook.com/profile.php?ref=bookmarks").userAgent(userAgent)
                .cookies(req.cookies()).get();
    
            System.out.println(d.body().text().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }