Mangiare Senza Glutine disponibile su App Store

Per altre informazioni scrivi a fabriziocaldarelli@negusweb.it

(English) Login Facebook from Java ( and J2ME )

Da Programmazione Software.

This simple class allow you to login to Facebook from Java, useful from mobile device where you develop using J"ME ( where are not available Facebook SDK to login )

Next PluginFacebook.java class and at bottom of article you can download entire project.

To use this class, you call static method:

PluginFacebook.CreateAndConnectAndLogin( __INSERT_EMAIL__ , __INSERT_PASSWORD__ );

that release PluginFacebook object from can get cookies to send in next http request to Facebook's pages with method:

Cookie2String()


PluginFacebook.java

package it.negusweb;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
 
 
public class PluginFacebook {
 
	Vector arrCookie;
	String email;
	String password;
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PluginFacebook.CreateAndConnectAndLogin( __INSERISCI_EMAIL__ , __INSERISCI_PASSWORD__ );
 
	}
 
	public PluginFacebook(String emailInput, String passwordInput)
	{
		this.email = emailInput;
		this.password = passwordInput;
 
		arrCookie = new Vector();
 
	}
 
	public String Cookie2String()
	{
		String strOut = "";
		String param = "";
 
		for(int k=0;k<arrCookie.size();k++)
		{
			param = (String) arrCookie.get(k);
			if (strOut == "") {
				strOut = param;
			} else {
				strOut = strOut + ";" + param;
			}
		}
 
		return strOut;
	}
 
 
	public static PluginFacebook CreateAndConnectAndLogin(String emailInput, String passwordInput)
	{
		PluginFacebook outObj = new PluginFacebook(emailInput, passwordInput);
 
		outObj.MakeCompleteConnection();
 
		return outObj;
	}
 
	private String ParseLoginFormAction(String htmlFacebook)
	{
		String strOut = "";
 
		int pos;
		String strDaElaborare;
		int posStartForm = htmlFacebook.indexOf("<form ");
		int posEndForm = htmlFacebook.indexOf("</form>");
 
		strDaElaborare = htmlFacebook.substring(posStartForm, posEndForm);
 
		int posTemp1 = strDaElaborare.indexOf("action=\"", 0);
		int posTemp2;
		if (posTemp1 != -1)
		{
			posTemp1 += 8;
			posTemp2 = strDaElaborare.indexOf("\"", posTemp1);
 
			strOut = strDaElaborare.substring(posTemp1, posTemp2);
		}		
 
		return strOut;
	}
 
	private Hashtable ParseLoginForm(String htmlFacebook)
	{
		String strDaElaborare;
		int posStartForm = htmlFacebook.indexOf("<form ");
		int posEndForm = htmlFacebook.indexOf("</form>");
 
		strDaElaborare = htmlFacebook.substring(posStartForm, posEndForm);
 
		Hashtable  hm = new Hashtable ();
 
		// Cerca il tag a e l'attributo href
		int pos = 0;
		int posTemp1 = 0;
		int posTemp2 = 0;
 
		int posTagInputStart=0;
		int posTagInputEnd=0;
		String htmlTagInput;
 
		String tagInputNome;
		String tagInputValore;
 
		while (pos != -1)
		{
			posTagInputStart = strDaElaborare.indexOf("<input ", pos);
			System.out.println("pos = "+pos+" - posStart = "+posTagInputStart);
			if (posTagInputStart!=-1)
			{
				posTagInputEnd = strDaElaborare.indexOf(">", posTagInputStart);
				if ((posTagInputEnd>posTagInputStart)&&(posTagInputStart!=-1))
				{
					htmlTagInput = strDaElaborare.substring(posTagInputStart, posTagInputEnd);
				}
				else
				{
					htmlTagInput = "";
 
				}
			}
			else
			{
				htmlTagInput = "";
				posTagInputEnd = -1;
			}
 
			if (htmlTagInput != "")
			{
 
				posTemp1 = htmlTagInput.indexOf("name=\"", 0);
				if (posTemp1 != -1)
				{
					posTemp1 += 6;
					posTemp2 = htmlTagInput.indexOf("\"", posTemp1);
					tagInputNome = htmlTagInput.substring(posTemp1, posTemp2);
					posTemp1 = htmlTagInput.indexOf("value=\"", 0);
					if (posTemp1 != -1)
					{
						posTemp1 += 7;
						posTemp2 = htmlTagInput.indexOf("\"", posTemp1);
						tagInputValore = htmlTagInput.substring(posTemp1, posTemp2);
 
						hm.put(tagInputNome, tagInputValore);
					}
				}
 
			}
			pos = posTagInputEnd;
		}	
 
		return hm;
	}
 
 
	 public void Login(String actionUrl, Hashtable parameters) 
	 {
 
			String location = "";
 
			HttpURLConnection httpConn = null;
 
			String url = actionUrl;
 
			InputStream is = null;
			OutputStream os = null;
 
			String key;
			String value;
			String param;
			String dataPOST = "";
			Enumeration keys = parameters.keys();
			while (keys.hasMoreElements()) {
				key = (String) keys.nextElement();
				value = (String) parameters.get(key);
				param = key + "=" + value;
				if (dataPOST == "") {
					dataPOST = param;
				} else {
					dataPOST = dataPOST + "&" + param;
				}
			}
 
			System.out.println("dataPOST:");
			System.out.println(dataPOST);
 
			try {
 
				// Open an HTTP Connection object
				URL urlObject = new URL(url);
				httpConn = (HttpURLConnection) urlObject.openConnection();
 
				// Setup HTTP Request to POST
				httpConn.setRequestMethod("POST");
 
				String cookie = this.Cookie2String();
 
				httpConn.setRequestProperty("Content-Type",	"application/x-www-form-urlencoded");
				httpConn.setRequestProperty("Content-Length",String.valueOf(dataPOST.length()));
				httpConn.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.1");
				httpConn.setRequestProperty("Accept-Charset", "UTF-8;q=0.7,*;q=0.7");
				httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
				httpConn.setRequestProperty("Accept","text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
				httpConn.setRequestProperty("Cookie", cookie);
 
				httpConn.setDoOutput(true);
				os = httpConn.getOutputStream();
				os.write(dataPOST.getBytes());
 
				/**
				 * Caution: os.flush() is controversial. It may create unexpected
				 * behavior on certain mobile devices. Try it out for your mobile
				 * device
				 **/
 
				// os.flush();
 
				// Read Response from the Server
 
				StringBuffer sb = new StringBuffer();
				is = httpConn.getInputStream();
				int chr;
				while ((chr = is.read()) != -1)
					sb.append((char) chr);
 
				System.out.println("RETURN FACEBOOK LOGIN");
				System.out.println(sb.toString());
 
				location = httpConn.getHeaderField("Location");
				System.out.println("Location: " + location);
 
				EstraiCookie(httpConn);
 
				// Web Server just returns the birthday in mm/dd/yy format.
				// System.out.println(name+"'s Birthday is " + sb.toString());
				if (is != null)
					is.close();
				if (os != null)
					os.close();
				if (httpConn != null)
					httpConn.disconnect();
 
			} catch (Exception excp) {
				excp.printStackTrace();
			}
 
			if (location != "") {
				this.HandleRedirect(location);
			}
	    }	
 
		public void HandleRedirect(String url)
		{
			String location = "";
			StringBuffer buffer = new StringBuffer();
			int chi;
			try
			{
				String cookie = this.Cookie2String();
				URL urlObj = new URL(url);
				HttpURLConnection hc = (HttpURLConnection)urlObj.openConnection();
				hc.setRequestProperty("Cookie", cookie);
 
				String s = hc.getResponseMessage();
 
				System.out.println("Cookie:");
				System.out.println(cookie);
 
				EstraiCookie(hc);
 
 
				int rc = hc.getResponseCode();
 
				if (rc==302)
				{
					location = hc.getHeaderField("Location");
				}
 
				if (hc.getResponseCode() == 200)
				{
					InputStream is = hc.getInputStream();
 
					do
					{
						chi = is.read();
						if (chi!=-1)
						{
							buffer.append((char)chi);
						}
					}while(chi!=-1);
 
					is.close();
				}
 
 
				hc.disconnect();
			}
			catch (Exception excp)
			{
				excp.printStackTrace();
			}
 
			System.out.println(buffer.toString());
 
			if (location != "")
			{
				this.HandleRedirect(location);
			}
		}	 
 
		public void EstraiCookie(HttpURLConnection hc)
		{
			String cookieTemp = "";
			String field = "";
			String headerName=null;
			Map<String, List<String>> m = hc.getHeaderFields();
 
			try
			{
				for (int i=1; hc.getHeaderField(i)!=null; i++) 
				{
					headerName = hc.getHeaderFieldKey(i);
				 	if (headerName.equals("Set-Cookie")) {                  
				 		field = hc.getHeaderField(i);
				 		cookieTemp = field.substring(0,field.indexOf(";"));
				 		System.out.println("cookieTemp="+cookieTemp);
 
				 		if(!this.arrCookie.contains(cookieTemp))
				 		{
				 			this.arrCookie.add(cookieTemp);
				 		}
 
				 	}
				}
			}
			catch(Exception excp)
			{
				excp.printStackTrace();
			}
 
		}
 
	public void MakeCompleteConnection()
	{
		StringBuffer buffer = new StringBuffer();
		int chi;
		try
		{
			long msInizio = System.currentTimeMillis();
			System.out.println("Inizio: "+msInizio);
 
			URL urlObj = new URL("http://m.facebook.com");
			HttpURLConnection hc = (HttpURLConnection) urlObj.openConnection();
 
			EstraiCookie(hc);
 
 
			String s = hc.getResponseMessage();
 
			if (hc.getResponseCode() == 200)
			{
				InputStream is = hc.getInputStream();
 
				do
				{
					chi = is.read();
					if (chi!=-1)
					{
						buffer.append((char)chi);
					}
				}while(chi!=-1);
 
				is.close();
			}
 
 
			long msFine = System.currentTimeMillis();
			System.out.println("Fine: "+msFine);
 
 
			hc.disconnect();
		}
		catch (Exception excp)
		{
			excp.printStackTrace();
		}
 
		System.out.println(buffer.toString());
		Hashtable parameters = this.ParseLoginForm(buffer.toString());
		String actionUrl = this.ParseLoginFormAction(buffer.toString());
 
		parameters.put("email", this.email);
		parameters.put("pass", this.password);
 
		this.Login(actionUrl, parameters);
 
		int a = 0;
	}
 
}

To download project: Facebook Login from Java ( and J2ME )