As you may or may not know, I’m working on a Java based Twitter client recently. Sending and getting data from Twitter is really, really simple. Here is how to do it in Java.
Let’s assume that we are trying to post an update to twitter with the following data:
String username = "someone@example.com";
String password = "password";
String status = "Look! I'm twittering using Java";
Twitter uses basic HTTP authentication which requires you to send a username:password pair encoded in base64:
String cridentials = new sun.misc.BASE64Encoder().encode((username + ":" + password).getBytes());
Now let’s create a HTTP connection:
URL url = new URL("http://twitter.com/statuses/update.xml");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
Authentication is activated like so:
conn.setRequestProperty ("Authorization", "Basic " + cridentials);
Now we can send the update by simply writing to conn’s output stream:
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
Finally, if you wand you can grab and print out the XML response sent back to you by Twitter server:
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line, output = "";
while ((line = rd.readLine()) != null)
{
System.out.println(output);
}
That’s it – that’s all you need to do.
[tags]twitter, java, jtwitt, java twitter client, twitter client, twiter updates[/tags]
That seems easier than a database connection/query :)
It really is. All you are doing is sending a HTTP request and receiving a response. As I illustrated before, you can do the same thing just using curl.
Thank you for using my image on your twitter page, but would you mind providing a link to either the page it came from (http://www.wellingtongrey.net/miscellanea/archive/2007-04-28–slashdot -flowchart.html) or the main site (http://www.wellingtongrey.net/) instead of just linking to the image directly?
Thank you,
-Grey
Sure thing boss. Link changed. :)
Btw, he is referring to this image.
I have tried the code and in the response it keeps returning my last post instead of updating the new status. Could this be just twitter?
Remember to flush your output stream. It worked for me when I tried it.
Pingback: Terminally Incoherent » Blog Archive » Problems with the DOMParser (s4s-elt-character Error)