Basic認証+JavaからTwitterにポスト
OAuth認証その2を書こうと思ったけど、なんとなく気分でBasic認証での投稿を試みてみた。
さくっとできた。OAuthに比べてすごい楽。
Basic認証を通過するにはAuthenticatorクラスを利用すると良さそうです。
Authenticatorのサブクラスを作成し、getPasswordAuthentication()をオーバーライドします。
下のソースではBasicAuthenticatorというクラスを作成し、そのインスタンスを引数として
Authenticator.setDefault(Authenticator)を呼出しています。
あとはTwitterのAPIを叩くのみ。
http://twitter.com/statuses/update.xmlに対し、URLエンコードしたstatusパラメータをPOSTで渡しています。
これで投稿完了です。
メインのクラスです。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; public class Basic { public static void main(String[] args) { String user = "user"; String password = "password"; try { URL url = new URL("http://twitter.com/statuses/update.xml?status=" + URLEncoder.encode("API+BASIC認証でテスト投稿", "UTF-8")); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); Authenticator authenticator = new BasicAuthenticator(user, password); Authenticator.setDefault(authenticator); connection.setRequestMethod("POST"); connection.connect(); int responseCode = connection.getResponseCode(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ } } }
Basic認証用のクラス(Authenticator)のサブクラスです。
import java.net.Authenticator; import java.net.PasswordAuthentication; public class BasicAuthenticator extends Authenticator { private String password; private String user; public BasicAuthenticator(String user, String password){ this.password = password; this.user = user; } protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(user, password.toCharArray()); } }
とまあこれで投稿自体はできるんですが。。。
これがタイムラインに投稿が反映された図です。「○○で」というところに注目してみてください。
「APIで」ってなってますね。
一方OAuthで投稿した図
「tvvitterで」ってなってますよね。
「tvvitter」というのは前もってTwitterに登録していた私専用の名前です。
「Webで」とか「movatwitterで」とか「twitbirdで」とかに混じって自分オリジナルのクライアント名が表示されるのちょっとうれしくないですか!?
セキュリティ的にもOAuthのほうが断然優位ですが、正直いって自分的にはこれが一番のモチベーションw
ということで次回以降はOAuth認証について書きます。たぶん。