Java twitter post status

import java.net.URLEncoder;

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;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

public class JavaRestTweet {
    private static final String CONSUMER_KEY_STR = "";
    private static final String CONSUMER_SECRET_STR = "";
    private static final String ACCESSTOKEN_STR = "";
    private static final String ACCESSTOKEN_SECRET_STR = "";
    private static final String API_URL = "https://api.twitter.com/1.1/statuses/update.json?status=";

    public static void main(String[] args) throws Exception {
        postTweet("Hi Twitter - test");
    }

    public static void postTweet(String message) throws Exception {
        OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY_STR, CONSUMER_SECRET_STR);
        oAuthConsumer.setTokenWithSecret(ACCESSTOKEN_STR, ACCESSTOKEN_SECRET_STR);

        HttpPost httpPost = new HttpPost(API_URL + URLEncoder.encode(message, "UTF-8"));
        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()));

    }
}

No comments:

Post a Comment