Simplest way to post Twitter status update to a dedicated account in Java
I am looking for a very simple way to post status updates to a dedicated Twitter account.
Currently we are using a POST request to https://api.twitter.com/1/statuses/update.xml with https basic auth. But Twitter is going to disable this API: http://apiwiki.twitter.com/Authentication
This oauth stuff is really, really complicated and not explained well at all.
I tried to use signpost but after playing around with that for hours, all I get is a 401.
OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1);
consumer.setTokenWithSecret(accessToken, tokenSecret);
URL url = new URL("https://api.twitter.com/1/statuses/update.xml");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Setup the header for the request
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Status Updater");
consumer.sign(connection);
// write the message
connection.setDoOutput(true);
OutputStream os = connection.getOutp开发者_如何学编程utStream();
os.write(("status=" + message.substring(0, Math.min(message.length(), 139))).getBytes("UTF-8"));
os.close();
// send the request
connection.getInputStream().close();
I had much better luck with Twitter4J than with Signpost. The core jar is only 300k, and it's also Google App Engine and Android (this is actually where I've used it) compatible. It's well-maintained; it supported xAuth from pretty much day one. And there are some good code examples on their website.
Just in case you want to see real code, here's the source for the app I implemented this for.
Seems like there is going to be a high demand for "simplifying" oauth for all the dedicated twitter accounts that use an external app. to post to a single account.
For a full oauth cycle using signpost's you'll need to make three requests the first time, after that you'll only need to make the last request to use your access token.
Pulling some stuff from a test app. I wrote, your "quick and dirty" oauth code should look something like this...
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import oauth.signpost.OAuth
import oauth.signpost.OAuthConsumer
import oauth.signpost.OAuthProvider
import oauth.signpost.basic.DefaultOAuthConsumer
import oauth.signpost.basic.DefaultOAuthProvider
api_url = "http://twitter.com/statuses/user_timeline.xml"
callback_url = "OOB"
provider = new DefaultOAuthConsumer(key, secret);
consumer = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
auth_url = provider.retrieveRequestToken(consumer, callback_url);
# Visit the auth_url and authorize that token manually
# oauth_verifier should be the digits returned by twitter for OOB authorization
provider.retrieveAccessToken(consumer, oauth_verifier);
access_token = consumer.getToken()
access_secret = consumer.getTokenSecrect()
# Finally, make your request...
url = new URL(api_url)
connection = url.openConnection()
consumer.sign(connection)
connection.connect()
# In case you wanted to get the data/response.
response = connection.getResponseMessage()
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
line = ''
results = ''
while ((line = reader.readLine()) != NULL) {
results += line;
}
reader.close()
I left the variable declarations off because I was using signpost through php (don't ask), but all the API calls should be correct.
Here's my code. I created an application in twitter (i require posting to only my twitter account), and received consumer key, consumer secret, twitter access token and twitter access token secret from 'Twitter application settings' and 'my twitter access token' screens. In applications settings, set default access type to read and write.
public void postToTwitter(String message) {
try {
ConfigurationBuilder confbuilder = new ConfigurationBuilder();
confbuilder.setOAuthAccessToken(TWITTER_ACCESS_TOKEN_HERE)
.setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET_HERE)
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_HERE)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_HERE);
Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance();
Status status = twitter.updateStatus(message);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
} catch (Exception e) {
e.printStackTrace();
}
}
This works great if you want to post to your own twitter account, and bypasses the complicated programmatic steps you'd otherwise require if you were to access the keys programmatically.
精彩评论