serving the solutions day and night

Wednesday, May 19, 2010

Tweets to your Twitter using REST API services - PHP, JAVA, C#.NET

I am on Twitter world, it is a kind of one awesome! social networking or mini blogging service or WEB 2.0 that enables its users to send and read messages knows as tweets.

It is text based messages of up to 140 characters or less displayed on the yours profile and delivered to your followers. Most of the users send and receive tweets via SMS, Twitter website, linkedin and other sources.



Using the Twitter REST API has some certain restrictions, not to do whatever you want. Authentication is required to access certain Twitter functions, which means you must include your credentials in the request. Otherwise, you will get a error status code 401.

Twitter supports both HTTP Basic and OAuth authentication. HTTP Basic authentication means that the request your user name or email and password in an encrypted format. OAuth authentication means that the requests is secured. For more details about OAuth authentication, read Twitter Authentication. Sure i will write next blog about Twitter OAuth authentication

Below the simple script can tweets to your twitter via API. Pass your twitter username or email, password and messages.

Twitter HTTP Status Codes
* 200 OK: Success!
* 304 Not Modified
* 400 Bad Request
* 401 Unauthorized
* 403 Forbidden
* 404 Not Found
* 406 Not Acceptable
* 420 Enhance Your Calm
* 500 Internal Server Error
* 502 Bad Gateway
* 503 Service Unavailable

Retrieving makdns Twitter timeline
http://twitter.com/statuses/user_timeline.xml?id=makdns
http://twitter.com/statuses/user_timeline.atom?id=makdns

PHP Code - make sure that you installed Curl Extension
<?php
  tweetsAPI('USER NAME OR EMAIL', 'PASSWORD', 'YOUR TWEETS POST');
  function tweetsAPI($sUsername, $sPassword, $sMessage)
  {
    if(strlen($sMessage) > 140)
      $sMessage = substr($sMessage, 0, 140);
    $sMessage = htmlentities(trim(strip_tags($sMessage)));
    if (!empty($sUsername) && !empty($sPassword) && !empty($sMessage))
    {
      $sTwitterURL = 'http://www.twitter.com/statuses/update.xml';
      $oCurlHandle = curl_init();
      curl_setopt($oCurlHandle, CURLOPT_URL, "$sTwitterURL");
      curl_setopt($oCurlHandle, CURLOPT_CONNECTTIMEOUT, 2);
      curl_setopt($oCurlHandle, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($oCurlHandle, CURLOPT_POST, 1);
      curl_setopt($oCurlHandle, CURLOPT_POSTFIELDS, "status=$sMessage");
      curl_setopt($oCurlHandle, CURLOPT_USERPWD, "$sUsername:$sPassword");
      curl_exec($oCurlHandle);
      $aOutput = curl_getinfo($oCurlHandle);
      if ($aOutput['http_code'] == 200)
        echo 'Your message has been tweet';
      else
        echo 'Could not tweet your message to Twitter.';
      curl_close($oCurlHandle);
    }
    else
    {
      echo('Missing information, please check it.');
    }
  }
?>

JAVA Code
<%@ page import="java.util.*, java.io.*,java.net.*, sun.misc.BASE64Encoder"%>
<%=tweetsAPI("USER NAME OR EMAIL", "PASSWORD", "YOUR TWEETS POST")%>
<%!
  private String tweetsAPI(String sUsername, String sPassword, String sMessage)
  {
    String strOutput="";
    StringBuffer sbStatus = new StringBuffer();
    String sTwitterURL = "http://www.twitter.com/statuses/update.xml";
    String sUSERPWD = "Basic " + new String(new sun.misc.BASE64Encoder().encode((sUsername + ":" + sPassword).getBytes()));
    if(sMessage.length() > 140)
        sMessage = sMessage.substring(0,140);

    if (sUsername!=null && sPassword!=null && sMessage!=null)
    {
      try
      {
        sbStatus.append(URLEncoder.encode("status", "UTF-8")).append("=").append(URLEncoder.encode(sMessage, "UTF-8"));
        byte[] bytes = (sbStatus.toString()).getBytes("UTF-8");
        URL oURLHandle = new URL(sTwitterURL);
        OutputStream osw = null;
        HttpURLConnection oURLConn = (HttpURLConnection) oURLHandle.openConnection();
        oURLConn.setDoInput(true);
        oURLConn.addRequestProperty("Authorization", sUSERPWD);
        oURLConn.setRequestMethod("POST");
        oURLConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        oURLConn.setDoOutput(true);
        oURLConn.setRequestProperty("Content-Length",Integer.toString(bytes.length));
        osw = oURLConn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        osw.close();
        if (oURLConn.getResponseCode()==200)
          strOutput = "Your message has been tweet";
        else
          strOutput = "Could not tweet your message to Twitter.";
      }
      catch (Exception e)
      {
        strOutput = e.toString();
      }
    }
    else
    {
      strOutput = "Missing information, please check it.";
    }
    return strOutput;
  }
%>

JAVA Code - To read Twitter response header
Map<String, List<String>> responseHeaders = oURLConn.getHeaderFields();
for (String key : responseHeaders.keySet())
{
  List values = responseHeaders.get(key);
  for (String value : values)
  {
    if(null != key)
    {
    System.out.println(key + ": " + value);
    }
    else
    {
      System.out.println(value);
    }
  }
}

C#.NET Code
protected void Page_Load(object sender, EventArgs e)
{
  Response.Write(tweetsAPI("USER NAME OR EMAIL", "PASSWORD", "YOUR TWEETS POST"));
}

private String tweetsAPI(String sUsername, String sPassword, String sMessage)
{
  String strOutput ="";
  String sTwitterURL = "http://www.twitter.com/statuses/update.xml";
  if (sMessage.Length > 140)
    sMessage = sMessage.Substring(0, 140);
  sMessage = String.Format("&status={0}", sMessage);
  if (sUsername != null && sPassword != null && sMessage != null)
  {
    try
    {
      byte[] bytes = Encoding.UTF8.GetBytes(sMessage);
      WebRequest wrRequest = WebRequest.Create(sTwitterURL);
      wrRequest.ContentType = "application/x-www-form-urlencoded";
      wrRequest.ContentLength = bytes.Length;
      wrRequest.Credentials = new NetworkCredential(sUsername, sPassword);
      wrRequest.Method = "POST";
      ServicePointManager.Expect100Continue = false;

      wrRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
      HttpWebResponse wrResponse = (HttpWebResponse)wrRequest.GetResponse();
      if(wrResponse.StatusCode.ToString() == "OK")
        strOutput = "Your message has been tweet";
      else
        strOutput = "Could not tweet your message to Twitter.";
    }
    catch (Exception e)
    {
      strOutput = e.ToString();
    }
  }
  else
  {
    strOutput = "Missing information, please check it.";
  }
  return strOutput;
}

Twitter API Reponse
HTTP/1.1 200 OK
X-Runtime: 0.14141
ETag: "b91b613bbb0e3a80fb94d55842b4b415"
Content-Length: 2023
X-Transaction: 1274295373-50657-23356
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Last-Modified: Wed, 19 May 2010 18:56:13 GMT
X-Revision: DEV
Set-Cookie: _twitter_sess=BAh7CjoRdHJhbnNfcHJvbXB0MDoPY3JlYXRlZF9hdGwrCGx; domain=.twitter.com; path=/
Set-Cookie: lang=en; path=/
Set-Cookie: guest_id=127429; path=/; expires=Fri, 18 Jun 2010 18:56:13 GMT
Set-Cookie: k=109.24.189.121.1235675373403164; path=/; expires=Wed, 26-May-10 18:56:13 GMT; domain=.twitter.com
Connection: close
Server: hi
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Pragma: no-cache
Status: 200 OK
Date: Wed, 19 May 2010 18:56:13 GMT
Vary: Accept-Encoding
Content-Type: application/xml; charset=utf-8

9 comments:

Luis Sacristán said...

In a few days basic auth will not work anymore

http://apiwiki.twitter.com/OAuth-FAQ#WhenareyougoingtoturnoffBasicAuth

Best regards

Daynight said...

thanks, that was i mentioned it in bold letter, and also i will write about blog for oAuth authentication.

Prasant Kumar said...

check this out:

http://www.developertutorials.com/tutorials/php/writing-a-simple-twitter-client-using-the-php-zend-frameworks-oauth-library-zend-oauth-9-10-20/page1.html

A very good tutorial of using zend_outh library to access twitter api.

Carlo Beschi said...

thanks for sharing this prasant - a very good reading

Mala said...

In C# how can get recent tweets from Twitter account using Username,Password

Flowers Guy said...

Did you ever get around to writing an oAuth version of this post?

Anonymous said...

hi,
i hve used ur code iam getting the error stating tht "Response doesnot exist in current context".....plz help me......iam trying out thz for the past two days.....

Anonymous said...

hi ;;;;;;;;
i have used ur code in console in main itslf i doesnot use any method.bt iam getting the error as unauthorized(401).plz help me as soon as possible....urgent need

Todd Merritt said...

Has anyone found a resolution for the unauthorized(401) error?