JavaのHttpUrlConnectionでBasic認証を利用する方法
Basic認証+JavaからTwitterにポスト
Java, Twitter | 22:34 |
OAuth認証その2を書こうと思ったけど、なんとなく気分でBasic認証での投稿を試みてみた。
さくっとできた。OAuthに比べてすごい楽。
Basic認証を通過するにはAuthenticatorクラスを利用すると良さそうです。
Authenticatorのサブクラスを作成し、getPasswordAuthentication()をオーバーライドします。
下のソースではBasicAuthenticatorというクラスを作成し、そのインスタンスを引数として
Authenticator.setDefault(Authenticator)を呼出しています。
メインのクラスです。
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());
}
}
最終更新:2012年11月12日 21:41