HttpClientで認証の必要なAPIを叩いてみた
フレンドタイムラインを見るには認証が必要だそうで。一応XMLを貰ってくるところまでは出来ました。何故か日本語の部分が数値文字参照になってしまうので、その対策はまた後ほど考えます。AndroidSDKでやった時はどうしたんだったかな。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class AuthTest { public static void main(String[] args) { DefaultHttpClient client = new DefaultHttpClient(); // フレンドタイムラインAPIへのGET HttpGet httpGet = new HttpGet( "http://twitter.com/statuses/friends_timeline.xml"); // ユーザー名とパスワード Credentials cred = new UsernamePasswordCredentials("hogeuser", "hogepassword"); // 認証のスコープ。ホストとポート番号。80番=WWW用 AuthScope scope = new AuthScope("twitter.com", 80); client.getCredentialsProvider().setCredentials(scope, cred); BufferedReader bufedReader = null; try { HttpResponse httpResponse = client.execute(httpGet); bufedReader = new BufferedReader(new InputStreamReader(httpResponse .getEntity().getContent())); // レスポンスを表示 // 日本語が数値文字参照になってしまうのは後で考える System.out.println(httpResponse.getStatusLine()); for (String line; (line = bufedReader.readLine()) != null;) { System.out.println(line); } // 例外処理 何もしませんが } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { // この時だけ切断 httpGet.abort(); e.printStackTrace(); } finally { try { bufedReader.close(); } catch (IOException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } } }