Created
October 11, 2010 01:36
-
-
Save osima/619818 to your computer and use it in GitHub Desktop.
Twitter: OAuthの認証サンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// g100pon #12 Twitter: OAuthの認証サンプル | |
// | |
// このコードは以下のサンプル(java)の groovy への移植です. | |
// http://github.com/kaeppler/signpost-examples/tree/master/OAuthTwitterExample/ | |
// | |
// 使い方 : | |
// | |
// 0. tw_oauth.groovy(このファイル)の consumerKey と consumerSecret に必要な値(*1)を設定 | |
// 1. groovy tw_oauth にて実行します. | |
// 2. 途中でブラウザが起動します. | |
// (環境によっては起動しないことがあるので,その場合はターミナルに表示されたURLを手動でブラウザに入力) | |
// 3. 許可ボタンをクリックした上で, 次ページで表示された PIN Code をコピーします. | |
// 4. ターミナルに PIN Code をペースト. | |
// | |
// *1) consumerKey, consumerSecret について | |
// twitter でアプリケーション登録したときに与えられる値を設定する必要があります. | |
// アプリケーション登録は, https://twitter.com/apps/new にて行います。 | |
// 特に審査などはないらしくすぐに登録できるようなので興味がある方は是非お試しください. | |
// | |
@Grab(group='oauth.signpost', module='signpost-core', version='1.2.1') | |
import oauth.signpost.* | |
import oauth.signpost.basic.* | |
import java.awt.Desktop | |
// 0) ここにあなたのTwitterアプリケーションの値を設定する必要があります. | |
consumerKey = '' | |
consumerSecret = '' | |
// 1) | |
consumer = new DefaultOAuthConsumer( consumerKey,consumerSecret ) | |
provider = new DefaultOAuthProvider( | |
'https://twitter.com/oauth/request_token', | |
'https://twitter.com/oauth/access_token', | |
'https://twitter.com/oauth/authorize' | |
) | |
// 2) | |
println "Fetching request token from Twitter..." | |
authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND) | |
println "Request token: ${consumer.token}" | |
println "Token secret: ${consumer.tokenSecret}" | |
// 3) | |
try{ | |
Desktop.getDesktop().browse authUrl.toURI() | |
} | |
catch(Exception ex){} | |
println "Now visit:\n${authUrl}\n... and grant this app authorization" | |
println 'Enter the PIN code and hit ENTER when you\'re done:' | |
br = new BufferedReader(new InputStreamReader(System.in)) | |
pin = br.readLine(); | |
// 4) | |
println "Fetching access token from Twitter..." | |
provider.retrieveAccessToken(consumer, pin); | |
println "Access token: ${consumer.token}" | |
println "Token secret: ${consumer.tokenSecret}" | |
// 5) | |
url = new URL("http://twitter.com/statuses/mentions.xml"); | |
request = url.openConnection() | |
consumer.sign(request) | |
println "Sending request to Twitter..." | |
request.connect(); | |
println "Response: ${request.responseCode} ${request.responseMessage}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment