Show me the code! – By Davanum Srinivas

March 16, 2009

Post/Update Twitter status snippet (from java)

Filed under: Uncategorized — Davanum Srinivas @ 10:10 am

Snippet to post to twitter. Using sun.misc to avoid introducing another jar (say commons codec). Please feel free to use another Base64 implementation. Rest of the details will remain the same.

import sun.misc.BASE64Encoder;

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.net.URLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Twitter {
    public static void main(String[] args) throws Exception {
        if (args.length < 3) {
            System.out.println("Twitter <userid> <password> <message>");
            System.exit(-1);
        }

        URL url = new URL("https://twitter.com/statuses/update.xml");
        URLConnection connection = url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        String authorization = args[0] + ":" + args[1];
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = new String
                (encoder.encodeBuffer(authorization.getBytes())).trim();
        connection.setRequestProperty("Authorization", "Basic " + encoded);

        OutputStreamWriter out = new OutputStreamWriter(
                connection.getOutputStream());
        out.write("status=" + URLEncoder.encode(args[2], "UTF-8"));
        out.close();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        connection.getInputStream()));
        String response;
        while ((response = in.readLine()) != null) {
            System.out.println(response);
        }
        in.close();

    }
}

1 Comment »

  1. [...] in a “Build Successful” message. If Java is your thing, look at Davanum Srinivas’ post and for .NET, there is [...]

    Pingback by Build Management 2.0 - Messaging — April 3, 2009 @ 7:43 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.