Tuesday, April 19, 2011

FaceBook Log In and Status Update in Netbin in java without Facebook API

package fb;

import java.net.MalformedURLException;

/**

 *

 * @author sharma */

public class login {

    

    public static void main (String[] args)

    {

        try

        {

            BasicApi fb = new BasicApi ("NAME@hotmail.com", "781899");

                

        }

        catch (MalformedURLException e)

        {

            e.printStackTrace();

        }

        catch (Exception e)

        {

        //    e.printStackTrace();

        }



    }



}




***********************************************************************************
package fb;



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.CookieHandler;

import java.net.CookieManager;

import java.net.CookieStore;

import java.net.HttpCookie;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;

import java.net.UnknownServiceException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.StringTokenizer;

import java.util.logging.Level;

import java.util.logging.Logger;



import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

import org.jsoup.nodes.Element;

import org.jsoup.select.Elements;





/**

 *

 * @author sharma

 */

public class BasicApi 

{



   Map<String,String> cookies = new HashMap<String, String>();



    private static final String SET_COOKIE = "Set-Cookie";

    private static final String COOKIE_VALUE_DELIMITER = ";";

    private static final String SET_COOKIE_SEPARATOR="; ";

    private static final String COOKIE = "Cookie";

    private static final char NAME_VALUE_SEPARATOR = '=';

        private String FB_BASE = new String ("http://www.facebook.com");

    private String FB_LOGIN_PAGE = new String ("/login.php");

    private String FB_HOME_PAGE = new String ("/home.php");

    private String FB_CHAT_WIN = new String ("/presence/popout.php");

    private String USER_AGENT = new String ("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.2");

    private String FB_POST_FORM = new String ("<input type=\"hidden\" id=\"post_form_id\"name=\"post_form_id\" value=");

    

    private String user = null;                

    private String post_form_id = null;        

    private String channel = null;            

    private int seq = -1;                    

    private URL basePage = null;            

    private CookieHandler cm = null;

        OutputStreamWriter out = null;

    URL login = null;

    HttpURLConnection loginConn = null;

    

    public BasicApi (String uname, String password) throws MalformedURLException

    {

            user = new String ("");

            post_form_id = new String ("");

            channel = new String ("");

            basePage = new URL (FB_BASE);

            initCookieManager();

        

            this.login(uname, password);

            this.getInfos();

            this.MyupdateStatus("this assignment is done");

        

    }

    

    public void login (String uname, String password)

    {

        try

        {    

            

            System.out.println("--------------LOGIN:----------------");

            

            

            login = new URL (basePage, FB_LOGIN_PAGE);

            HttpURLConnection.setFollowRedirects(false);            //Sets whether HTTP redirects should be automatically followed by this class

            loginConn = openConnection(login);

            System.out.println ("Response Code :" + loginConn.getResponseCode());       // Gets the status code from an HTTP response message

            

            loginConn.getContent();

            loginConn.disconnect();

            

            printCookies(loginConn);

            loginConn = openConnection(login);

            loginConn.setRequestMethod("POST");                         //Get the request method

            loginConn.setDoOutput(true);                                // A URL connection can be used for input and/or output. Set the DoOutput flag to true if

                                            // you intend to use the URL connection for output, false if not. The default is false.



                        out = new OutputStreamWriter(loginConn.getOutputStream());  //  Returns an output stream that writes to this connection

            out.write("email=" + uname + "&pass=" + password);

            out.flush();                                                // Flush the stream.

            out.close();

            

            loginConn.disconnect();

            

            System.out.println ("Response Code :" + loginConn.getResponseCode());    //Gets the status code from an HTTP response message. For example, in the case of the following status lines:  HTTP/1.0 200 OK  HTTP/1.0 401 Unauthorized

             System.out.println ("Request Method :" +loginConn.getRequestMethod());    //Get the request method.

            

            printCookies(loginConn);

            System.out.println("-------------------END LOGIN----------------------");

                        

        }

        catch (MalformedURLException e)

        {

            System.out.println ("error: " + e.getCause());

        }

        catch (UnknownServiceException e)

        {

            System.out.println ("Error: ");

        }

        catch (IOException e)

        {

            System.out.println ("Error: ");

            e.printStackTrace();

        }

    }

    

    

    public void getInfos ()

    {

        try

        {

            System.out.println ("------------------------GET INFOS-------------------");

            URL infopage = null;

            HttpURLConnection infoConn = null;

            BufferedReader read = null;

            String line = null;

            

            int pfStart = -1, pfEnd = -1;

            CookieStore cs = ((CookieManager)cm).getCookieStore();

            

            

            for (HttpCookie c : cs.getCookies()){

                if (c.getName().equals("c_user")){

                    user += c.getValue();

                    break;

                }    

            }

            

            

            if (this.user.equals(""))   System.out.println("Login ");

            else    System.out.println("user id: " + user);

            

            infopage = new URL(basePage, FB_CHAT_WIN);

            infoConn = openConnection(infopage);

            read = new BufferedReader(new InputStreamReader (infoConn.getInputStream()));



            while ((line = read.readLine()) != null){



                if (line.startsWith(FB_POST_FORM)){



                    pfStart = line.indexOf("value=");

                    pfStart = line.indexOf("\"", pfStart);

                    pfStart ++;

                    pfEnd = line.indexOf("\"", pfStart);

                    post_form_id = line.substring(pfStart, pfEnd);

                }

                            

            }



            

            if (post_form_id == null)       System.out.println("impossibile post_form_id");

            else                            System.out.println("post form: " + post_form_id);

            

            System.out.println ("----------------END GET INFOS--------------");

            

        }

        catch (MalformedURLException e)

        {

            System.out.println ("error: " + e.getCause());

        }

        catch (IOException e)

        {

            System.out.println ("errore ");

            e.printStackTrace();

        }

    }

    void getCookies(URLConnection fbConn)

    {

        String headerName;

        for(int i=1;(headerName = fbConn.getHeaderFieldKey(i))!=null;i++)

        {

            if(headerName.equalsIgnoreCase(SET_COOKIE))

            {

                StringTokenizer tokens = new StringTokenizer(fbConn.getHeaderField(i),COOKIE_VALUE_DELIMITER);

                while(tokens.hasMoreTokens())

                {

                    String token=tokens.nextToken();

                    try

                    {

                        String key = token.substring(0,token.indexOf(NAME_VALUE_SEPARATOR));

                        key = key.replaceAll(" ","");

                        if(!key.equalsIgnoreCase("expires") && !key.equalsIgnoreCase("path") && !key.equalsIgnoreCase("domain"))

                        {

                            String value=token.substring(token.indexOf(NAME_VALUE_SEPARATOR)+1,token.length());

                            cookies.put(key, value);

                        }

                    }

                    catch(Exception e){}

                }

            }

        }

    }



    void setCookies(URLConnection fbConn)

    {

        StringBuffer cookieNames=new StringBuffer();

        Iterator it=cookies.keySet().iterator();

        while(it.hasNext())

        {

            String key=(String) it.next();

            String value=cookies.get(key);

            cookieNames.append(key);

            cookieNames.append("=");

            cookieNames.append(value);



            if(it.hasNext())

            {

                cookieNames.append(SET_COOKIE_SEPARATOR);

            }

        }

        //System.out.println(cookieNames.toString());



        fbConn.setRequestProperty(COOKIE,cookieNames.toString());

    }



    void viewCookiews()

    {

        System.out.println("Cookie Size : " +cookies.size());

        Iterator it=cookies.keySet().iterator();

        while(it.hasNext())

        {

            String key=(String) it.next();

            String value=cookies.get(key);

            System.out.println(key + " : "+value);

        }

    }



    String MygetPageContent(URLConnection fbConn)

    {

        String contents = "";

        BufferedReader in = null;



        try

        {

            in = new BufferedReader(new InputStreamReader(fbConn.getInputStream()));

            String inputLine;



            while ((inputLine = in.readLine()) != null)

            {

                contents += inputLine + "\r\n";

            }

            in.close();

        }

        catch (IOException ex)

        {

            ex.printStackTrace();

            Logger.getLogger(BasicApi.class.getName()).log(Level.SEVERE, null, ex);

        }



        finally

        {

            try

            {

                in.close();

            }

            catch (IOException ex)

            {

                ex.printStackTrace();

                Logger.getLogger(BasicApi.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

        return contents;

    }

    Map<String,String> MygetStatusUpdateParamiters(String html)

    {

        Map<String,String> paramiters=new HashMap<String, String>();



        Document doc = (Document) Jsoup.parse(html);

        Element dom = doc.getElementById("composer_form");

        Elements inputs=dom.getElementsByTag("input");

        for(int i=0;i<inputs.size();i++)

        {

            System.out.println(inputs.get(i).attr("name")+" : "+inputs.get(i).attr("value"));

            paramiters.put(inputs.get(i).attr("name"),inputs.get(i).attr("value"));

        }



        return paramiters;

    }

     void MyupdateStatus(String status)

    {

        URLConnection fbStatusCon = null;

        URL fbStatusURL = null;

        OutputStreamWriter wr = null;



        try {



            URL url = new URL("http://m.facebook.com/profile.php?refid=7");

          //  URL url = new URL("http://www.facebook.com/profile.php?id=100001616376884");



            URLConnection con = url.openConnection();

            setCookies(con);

            con.connect();

            getCookies(con);

            String profilePageContent=MygetPageContent(con);

            //System.out.println(getPageContent(con));



            System.out.println("view Profile page successfull");



            fbStatusURL = new URL("http://www.facebook.com/ajax/updatestatus.php");

            fbStatusCon = fbStatusURL.openConnection();

            setCookies(fbStatusCon);



            fbStatusCon.setDoOutput(true);

            wr = new OutputStreamWriter(fbStatusCon.getOutputStream());

            Map<String , String> parameters=new HashMap<String,String>();



            parameters=MygetStatusUpdateParamiters(profilePageContent);

            Iterator it=parameters.keySet().iterator();



            String data="status="+URLEncoder.encode(status, "UTF-8");

            while(it.hasNext())

            {

                String key=(String) it.next();

                String value=parameters.get(key);



                data+="&"+key+"="+URLEncoder.encode(value, "UTF-8");

            }



            /*String post_form_id = "80a8de91bf3c0e413e96e5b964ae4753";

            String fb_dtsg = "1pghv";

            String update = "Share";

            String charset_test = "€,´,€,´,?,?,?";



            String data="post_form_id="+URLEncoder.encode(post_form_id, "UTF-8");

            data+="&fb_dtsg="+URLEncoder.encode(fb_dtsg, "UTF-8");

            data+="&status="+URLEncoder.encode(status, "UTF-8");

            data+="&update="+URLEncoder.encode(update, "UTF-8");

            data+="&charset_test="+URLEncoder.encode(charset_test, "UTF-8");*/



            wr.write(data);

            wr.flush();

            wr.close();



            fbStatusCon.connect();

            getCookies(fbStatusCon);

            //System.out.println("Contents : \n"+getPageContent(fbStatusCon));

            System.out.println("status Update successfull");

            viewCookiews();

        } catch (IOException ex) {

        }

    }

    

    public void send (String to, String text)

    {

        

        

    }

    

    private void initCookieManager ()

    {

        cm = new MyCookieManager();

        java.net.CookieHandler.setDefault(cm);        

    }



    

    private HttpURLConnection openConnection (URL u) throws IOException

    {

        HttpURLConnection conn = (HttpURLConnection)u.openConnection();

        setUserAgent(conn);

        return conn;    

    }

    

    

    private void setUserAgent (URLConnection u)

    {

        u.setRequestProperty("User-Agent", USER_AGENT);    

    }

    

    

    private void printCookies (HttpURLConnection conn)

    {

        CookieStore cs = ((CookieManager)cm).getCookieStore();

        

        int i = 0;

        System.out.println ("----------Cookies--------------");

        for (i = 0; i < 99; i++)

        {

            String s = conn.getHeaderFieldKey(i);

            

            if (s != null && s.equals("Set-Cookie"))

            {

                System.out.println ("Set-Cookie: " + conn.getHeaderField(i));

            }

                

            

        }

        

        System.out.println("-------------------------------");

        

        for (HttpCookie c : cs.getCookies())

            System.out.println (c.toString());

        

        System.out.println("-------------------------------------------");

    }

    

}





**********************************************************************************
package fb;

import java.io.IOException;

import java.net.*;

import java.util.*;



/**

 * * @author sharma

*

 */

public class MyCookieManager extends CookieManager

{



    public MyCookieManager ()

    {

        super();    

    }

    

    public MyCookieManager(CookieStore store,

            CookiePolicy cookiePolicy)

    {

        super (store, cookiePolicy);

    }

    

     @Override

    public void put(URI uri, Map<String, List<String>> responseHeaders)

                                                        throws IOException

    {



        Map <String, List<String>> newHeader = 

                                    new HashMap <String, List<String>>();

        

        List <String> temp = null, newList = new LinkedList <String>();

        



        temp = responseHeaders.get("Set-Cookie");

        



        if (temp != null)

        {



            for (String s : temp)

                newList.add(s.replace("; httponly", ""));

            



            newHeader.put("Set-Cookie", newList);

                    newList = new LinkedList <String>();

        }

        

        

        temp = responseHeaders.get("Set-Cookie2");

        

        if (temp != null)

        {

            for (String s : temp)

                newList.add(s.replace("; httponly", ""));

            

            newHeader.put("Set-Cookie2", newList);

        }

        



        super.put(uri, newHeader);

    }

}






1 comment:

  1. You done very well job. But status not update. please help....

    ReplyDelete

How to enable hotspot in TPG iPhone

 By default, the hotspot does not work on the phone. It will ask you to contact the provider. This video will help you bypass the network ...