apache HttpClient to access facebook

橙三吉。 提交于 2019-11-29 15:00:12
Piotr Kochański

The following code, based on that sample, worked for me:

DefaultHttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");

HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();

System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
    entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
    System.out.println("None");
} else {
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("- " + cookies.get(i).toString());
    }
}

HttpPost httpost = new HttpPost("http://www.facebook.com/login.php");

List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "******"));
nvps.add(new BasicNameValuePair("pass", "*******"));

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Double check we've got right page " + EntityUtils.toString(entity));

System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
    entity.consumeContent();
}

System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
    System.out.println("None");
} else {
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("- " + cookies.get(i).toString());
    }
}

httpclient.getConnectionManager().shutdown();  

I am not sure if your code was managing properly cookies (and session id kept within one of them), maybe that was the problem. Hope this will help you.

Just to make clear version issue: I was using HttpClient version 4.X, not the old one (3.X). They differ significantly.

Perhaps you should use a tool, such as Selenium

Have you taken a look at HtmlUnit. It wraps the HttpClient to create a headless Java browser, with javaScript execution. This way you are not trying to hack the individual forms all the time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!