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;


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

        URL url = new URL("");
        URLConnection connection = url.openConnection();


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

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

        BufferedReader in = new BufferedReader(
                new InputStreamReader(
        String response;
        while ((response = in.readLine()) != null) {



  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

  2. I am getting the error : Server returned HTTP response code: 401 for URL:

    when i am trying to run this code as a standalone application

    Comment by kiran — November 30, 2010 @ 4:36 am

  3. I tried to execute this program and i got the following exception:
    Exception in thread “main” Server returned HTTP response code: 401 for URL:
    What could be the issue?

    Comment by Teja — December 9, 2010 @ 3:14 pm

  4. i also run above code and i getting the below what can i do ?please help me..


    Exception in thread “main” Server returned HTTP response code: 401 for URL:
    at Source)
    at Source)
    at twxa.Twitter.main(

    Comment by lingadurai — July 15, 2011 @ 12:37 am

  5. Error 401 means that you do not have access, did you pass the right arguments to the program (login and password), see line 24?
    See the different HTTP response codes on Twitter:

    If that does not fix the problem, take a look at line 26, and make sure (while debugging) that there is not “\n\r” appended to the encoded variable.

    Comment by Ted Gueniche — December 18, 2011 @ 9:16 am

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

%d bloggers like this: