LoginSignup
14
15

More than 5 years have passed since last update.

Volley+oauth-signpostでOAuthリクエスト

Posted at

Volley上でOAuthリクエストするときに便利なHttpStackを書きました。

OAuthHurlStack.java
public class OAuthHurlStack extends HurlStack {

    private final OAuthConsumer consumer;

    public OAuthHurlStack(OAuthConsumer consumer) {
        this.consumer = consumer;
    }

    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            this.consumer.sign(connection);
        } catch (OAuthMessageSignerException e) {
            // TODO: OAuthMessageSignerExceptionハンドリングを実装
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            // TODO: OAuthExpectationFailedExceptionハンドリングを実装
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            // TODO: OAuthCommunicationExceptionハンドリングを実装
            e.printStackTrace();
        }
        return connection;
    }
}
OAuthHttpClientStack.java
public class OAuthHttpClientStack extends HttpClientStack {

    private final OAuthConsumer consumer;

    public OAuthHttpClientStack(HttpClient client, OAuthConsumer consumer) {
        super(client);
        this.consumer = consumer;
    }

    @Override
    protected void onPrepareRequest(HttpUriRequest request) throws IOException {
        super.onPrepareRequest(request);
        try {
            this.consumer.sign(request);
        } catch (OAuthMessageSignerException e) {
            // TODO: OAuthMessageSignerExceptionハンドリングを実装
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            // TODO: OAuthExpectationFailedExceptionハンドリングを実装
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            // TODO: OAuthCommunicationExceptionハンドリングを実装
            e.printStackTrace();
        }
    }
}

signpostにcommonshttpを利用している場合はOAuthHttpClientStackを利用してください。

あとはいつもどおり

RequestQueue requestQueue = Volley.newRequestQueue(context, new OAuthHurlStack(consumer)) // consumerはOAuthConsumer

っとすればよいです。

14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15