GAE上でTiwtter4jを利用する OAuth認証(1)

Twitter REST API v1.1 Resources を直接利用してアプリケーションを開発する予定だったが、やらなければいけないことが多いので、Twitter4jを使って開発速度重視を考えた。
POSTするだけなんで、はまるはずが無いと思っていたのだが、認証までに2日(実質28時間)かかってしまった。まず、ローカル上でテストができないことと、サンプルコードとWeb上におちてるコードでは動かないことだった。
OAuth認証で必要なconsumerKeyとconsumerSecretの配置の問題が起こる。

Web上の公式サイトには、システムパラメータとして引き渡せると記述があったので、
GAEの WEB-INF/appengine-web.xml に配置すればいいと思い下記のように記述する。
<system-properties>
<property name="twitter4j.oauth.consumerKey" value="*******"/>
<property name="twitter4j.oauth.consumerSecret" value="********"/>
</system-properties>

自動的に読み込んでいるかは不明で、例外が発生する。
それで、
String key = System.getProperty("twitter4j.oauth.consumerKey");
String secret = System.getProperty("twitter4j.oauth.consumerSecret");

として、twitter.setOAuthConsumer(key,secret); を追加するが変わらない・・・
試行錯誤の結果、WEB-INF/appengine-web.xmlを変更すると、あらま処理できた。

以下が正常に処理できたソース
WEB-INF/appengine-web.xml
<system-properties>
<property name="consumerKey" value="*******"/>
<property name="consumerSecret" value="********"/>
</system-properties>


String key = System.getProperty("consumerKey");
String secret = System.getProperty("consumerSecret");
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(key,secret);
RequestToken reqToken = twitter.getOAuthRequestToken();
String strUrl = reqToken.getAuthorizationURL();
response.sendRedirect(strUrl);

はまらないために、システムパラメータのKey名は別ものとする

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>