Posting a Tweet in Java

Twitter offers an API that allows you to, among many things, post a tweet or status update. Doing so from my Java application was not entirely straightforward for me. I usually use the RestTemplate class supplied with Spring Boot. However, there seemed no obvious way to combine the use of the Spring RestTemplate with the OAuth1.0a authentication required by the Twitter API.

An alternative exists in the OAuth Signpost library.

First, include the dependency in your project:

<dependency>
<groupId>oauth.signpost</groupId>
<artifactId>signpost-commonshttp4</artifactId>
<version>2.1.1</version>
</dependency>

The procedure requires as much as 4 different keys and tokens: an API key, an API key secret, an Access token and and Access token secret. These can all be generated from your Twitter Developer portal under your Project app. Be sure to set your app permissions to read & write before you generate any access tokens.

The following code allows you to post a tweet using those strings. First initialize an OAuthConsumer, supplying it with the authentications just mentioned.

OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(API_KEY,
API_KEY_SECRET);
oAuthConsumer.setTokenWithSecret(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

Be sure to url encode your tweet:

String urlEncodedTweet = URLEncoder.encode("This is a test tweet",
StandardCharsets.UTF_8.toString());
String resourceUrl = "https://api.twitter.com/1.1/statuses/update.json;

Create a new HttpPost and sign it using the OAuthConsumer:

HttpPost httpPost = new HttpPost(String.format("%s?status=%s",
resourceUrl, urlEncodedTweet);
oAuthConsumer.sign(httpPost);

Initialize a new http client. (Obviously, if you're using Spring you may want to supply the method with the client in some other way.)

CloseableHttpClient httpClient = HttpClients.createDefault();

Now you can execute the request. It will return an HttpResponse object which contains information you may want to do something with.

HttpResponse response = httpClient.execute(httpPost);

This is all there is to it! If your authentication is valid, the response should contain a 200 OK status and your tweet should show up on your timeline right away.