Search code examples
facebookauthenticationhttpclient

Is it possible to login in Facebook login with Http Client in 2015?


There are several similar questions asked through the years, but even those posted sooner are not completely relevant to what I'm going to ask. The rest don't have answers or promote the usage of deprecated code and methods. So I don't consider my question a duplicate.

I'm trying to login with my personal FB credentials using Apache HttpClient for full search options which are not part of the Graph API (for example search by email, etc). So I'm pretty much asking if this is possible? It seems that it was possible back in the time.

I've tried lots of things in my code, so I'll paste just a short version of what I'm doing. The problem is that I always get an error message stating that Cookies are required and are not enabled.

I'm using Apache httpclient 4.4.1. Please don't paste me some code that you haven't tested. Ideas are welcome. I first make a GET request to the login page to retrieve the cookies, but no cookies are stored in the CookieStore no matter what cookie policy I'm setting or even if I'm adding the same http context to both requests:

CookieStore getCookieStore = new BasicCookieStore();
RequestConfig globalConfig = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.DEFAULT)
            .build();
HttpClient getHttpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(getCookieStore)
            .build();
BasicHttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, getCookieStore);

HttpGet getPageRequest = new HttpGet(FACEBOOK_LOGIN_URL);
getPageRequest.setHeader("User-Agent", "Mozilla/5.0");
getPageRequest.setHeader("Host", FACEBOOK_DOMAIN_URL);
getPageRequest.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,**/ *//*;q=0.8");
getPageRequest.setHeader("Accept-Language", "en-US,en;q=0.5");
getPageRequest.setHeader("Connection", "keep-alive");
getPageRequest.setHeader("Referer", FACEBOOK_LOGIN_URL);
getPageRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

getHttpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

// NO COOKIES HERE !!!
CookieStore postCookieStore = new BasicCookieStore();
    System.out.println("getCookieStore.getCookies().size(): " +   getCookieStore.getCookies().size());
getCookieStore.getCookies().forEach(postCookieStore::addCookie);

HttpClient postHttpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(postCookieStore)
            .build();

HttpPost loginRequest = new HttpPost(FACEBOOK_LOGIN_URL);
List<NameValuePair> loginCredentials = new ArrayList<>();

Document loginPageDocument = Jsoup.parse(getPageEntityString);
Elements hiddenInputElements = loginPageDocument.select("input[type=hidden]");
for (Element element : hiddenInputElements) {
    String id = element.id();
    String value = element.val();
    loginCredentials.add(new BasicNameValuePair(id, value));
}

loginCredentials.add(new BasicNameValuePair("email", EMAIL));
loginCredentials.add(new BasicNameValuePair("pass", PASS));

loginRequest.setEntity(new UrlEncodedFormEntity(loginCredentials));

loginRequest.setHeader("User-Agent", "Mozilla/5.0");
loginRequest.setHeader("Host", FACEBOOK_DOMAIN_URL);
loginRequest.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
loginRequest.setHeader("Accept-Language", "en-US,en;q=0.5");
loginRequest.setHeader("Connection", "keep-alive");
loginRequest.setHeader("Referer", FACEBOOK_LOGIN_URL);
loginRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

String loginEntityString = "";
try {
    HttpResponse loginResponse = postHttpClient.execute(loginRequest);
    HttpEntity loginEntity = loginResponse.getEntity();
    loginEntityString = EntityUtils.toString(loginEntity);
    EntityUtils.consume(loginEntity);
} catch (Throwable t) {
    System.err.println(t.getMessage());
} finally {
    loginRequest.releaseConnection();
}

System.out.println(loginEntityString);

Solution

  • The only possible way that I found to login into Facebook programmatically is using Selenium which may not be the best way for every application, but it's going to work for me. This is a working example of login into Facebook and searching for a key phrase. It may not be valid in the near future if the website's HTML get's changed.

        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("https://www.facebook.com/");
    
        driver.findElement(By.id("email")).sendKeys(YOUR_FACEBOOK_EMAIL);
        WebElement passInput = driver.findElement(By.id("pass"));
        passInput.sendKeys(YOUR_FACEBOOK_PASS);
        passInput.sendKeys(Keys.ENTER);
    
        WebElement searchInput = driver.findElement(By.cssSelector("[aria-label='Search Facebook']"));
        searchInput.sendKeys("YOUR_SEARCH_PHRASE");
    
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(presenceOfElementLocated(By.cssSelector("[aria-label='Search']")));
    
        WebElement searchButton = driver.findElement(By.cssSelector("[aria-label='Search']"));
        searchButton.click();