How to Post to Twitter Using Twitter REST API

Now we are all set to post to Twitter using Java. In this section, let us see how we can use the REST APIs directly in our Java application. Let us use the status update post Twitter API.

How to Post to Twitter Using Twitter REST API,Post to Twitter Using Twitter REST API,Twitter Using Twitter REST API,Twitter REST API,

All we need to do is,
Read this : How to use Twitter Consumer Key and Consumer Secret
To make these REST call lets use oauth-signpost and Apache Commons HTTP. Following are the dependent jars to be used,
  1. commons-codec-1.6.jar
  2. commons-io-2.4.jar
  3. commons-logging-1.1.3.jar
  4. httpclient-4.3.1.jar
  5. httpcore-4.3.jar
  6. signpost-core-1.2.1.2.jar
  7. signpost-commonshttp4-1.2.1.2.jar
package com.geekonjava.java;
 
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
 
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
 
public class JavaRestTweet {
  static String consumerKeyStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String consumerSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String accessTokenStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String accessTokenSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 
 
  public static void main(String[] args) throws Exception {
    OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr,
        consumerSecretStr);
    oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);
 
    HttpPost httpPost = new HttpPost(
        "http://api.twitter.com/1.1/statuses/update.json?status=Hello%20Twitter%20World.");
 
    oAuthConsumer.sign(httpPost);
 
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpPost);
 
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    System.out.println(statusCode + ':'
        + httpResponse.getStatusLine().getReasonPhrase());
    System.out.println(IOUtils.toString(httpResponse.getEntity().getContent()));
 
  }
}
Comment please to appreciate for more post !!!

No comments:

Post a Comment