Java™ カスタム・リソースの要求実装サンプル

このサンプルでは、カスタム HttpRequest オブジェクトおよび MobileFirst AuthorizationManager API を使用して、保護リソースからデータを取得する方法を示します。

サンプルは、標準の OAuth フローを実装します。最初に、リソース要求がアクセス・トークンなしで送信されます。この要求は許可エラーで失敗することが予想されます。次に、 WLAuthorizationManager を使用してリソースの保護スコープ用のアクセス・トークンを取得し、 取得したアクセス・トークンを許可ヘッダーとして使用して要求を再送します。リソース要求は、標準の HttpURLConnection オブジェクトを使用して作成されます。

package com.sample.oauthdemoandroid;

import android.os.AsyncTask;

import com.worklight.wlclient.api.WLAccessTokenListener;
import com.worklight.wlclient.api.WLAuthorizationManager;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.auth.AccessToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class CustomRequestAsyncTask extends AsyncTask<Object, Void, Void> {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    private Object[] params;

    @Override
    protected Void doInBackground(Object[] params) {
        android.os.Debug.waitForDebugger();  // for debugging
        this.params = params;
        sendRequest(null);
        return null;
    }

    private void sendRequest(AccessToken accessToken) {
        HttpURLConnection urlConnection = null;
        try {
            // Create the request to access the resource URL
            URL url = new URL(WLClient.getInstance().getServerUrl().toString() + params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            if (accessToken != null) {
                // Add an access token to the request
                urlConnection.setRequestProperty(HEADER_AUTHORIZATION, accessToken.getAsAuthorizationRequestHeader());
            }

            // Send the request
            Map<String, List<String>> headerFields = urlConnection.getHeaderFields();

            // Check whether the request succeeded
            int responseCode = urlConnection.getResponseCode();
            if (200 <= responseCode && responseCode <= 299) {
                customRequestSuccess(urlConnection);
            } else {
                // Check whether access to the resource requires authorization
                WLAuthorizationManager wlAuthorizationManager = WLAuthorizationManager.getInstance();
                if (wlAuthorizationManager.isAuthorizationRequired(responseCode, headerFields)) {
                    switch (responseCode) {
                        case 409: // Server-conflict error
                            // Resend the request
                            sendRequest(accessToken);
                            break;
                        case 401: // Invalid access token, or no access token
                            // Clear the access token (if exists)
                            if (accessToken != null) {
                                wlAuthorizationManager.clearAccessToken(accessToken);
                            }
                            // Obtain a valid access token and resend the request
                            resendWithAccessToken(headerFields);
                            break;
                        case 403: // Insufficient-scope error
                            // Get the resource scope from the response and resend the request
                            resendWithAccessToken(headerFields);
                            break;
                        default: // Unexpected error
                            customRequestFailure(urlConnection);
                    }

                } else {
                    customRequestFailure(urlConnection);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    private void customRequestSuccess(HttpURLConnection urlConnection) throws IOException {
        // TODO: Implement the method.
    }

    private void customRequestFailure(HttpURLConnection urlConnection) throws IOException {
        // TODO: Implement the method.
    }

    private void resendWithAccessToken(Map<String, List<String>> headerFields) {
        WLAuthorizationManager wlAuthorizationManager = WLAuthorizationManager.getInstance();
        // Get the resource request from the response
        String scope = wlAuthorizationManager.getResourceScope(headerFields);
        // Obtain an access token and resend the request
        CustomRequestObtainAccessTokenListener customRequestObtainAccessTokenListener = new CustomRequestObtainAccessTokenListener();
        wlAuthorizationManager.obtainAccessToken(scope, customRequestObtainAccessTokenListener);
    }

    private class CustomRequestObtainAccessTokenListener implements WLAccessTokenListener {

        @Override
        public void onSuccess(AccessToken accessToken) {
            sendRequest(accessToken);
        }

        @Override
        public void onFailure(WLFailResponse response) {
            // TODO: Implement the method.
        }
    }
}