Wednesday, December 9, 2009

Tweet from Java

Here's how you can use Twitter API to Tweet from java:


import java.io.*;
import java.net.*;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;


public class Tweet {
static String twitterUrl="http://twitter.com/statuses/update.xml";


public static void main(String[] args) throws Exception {
//Hate args checking.. Won't do it; Not even usage shall be displayed - figure it out
OutputStreamWriter ostreamwriter;
String statusmsg="";
int i=2;

URL url = new URL(twitterUrl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + Base64.encode((args[0]+":"+args[1]).getBytes()));
while(i < args.length-1){
statusmsg = statusmsg+ args[i++]+" ";
}
statusmsg = statusmsg+ args[i];
String encStatus = "status="+URLEncoder.encode(statusmsg, "UTF-8");
ostreamwriter = new OutputStreamWriter(conn.getOutputStream());
ostreamwriter.write(encStatus); //--> Magic Magic :)
ostreamwriter.flush();                              //I forgot this at first..

//If interested you can check the response after this, though
}
//Won't bother with exceptions either. 
//A programmer should be intelligent enough to discover errors without any display mechanisms...
}
}


And voilĂ :













(or you could also use this )

No comments:

Post a Comment