Wednesday, December 9, 2009

Tweet from Java

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


public class Tweet {
static String twitterUrl="";

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.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