Custom requests to resources using Java™

This sample demonstrates how to get data from a protected resource by using a custom HttpRequest object and the MobileFirst AuthorizationManager API.

After a response was first received, the WLAuthorizationManager class determines whether this response is a MobileFirst protocol response. If so, the user gets the scope, obtains the authorization header for this scope, and requests the protected resource one more time.

try {
    // Create an http client to send the request
    final DefaultHttpClient client = new DefaultHttpClient();

    // Create the request to send
    final HttpGet get = new HttpGet("http://localhost:3000/v1/apps/1234/test");

    // Send the request and get the response
    HttpResponse response = client.execute(get);

    // Check that the response conforms to the MFP protocol
    if (WLAuthorizationManager.getInstance().isAuthorizationRequired(response)){

        // Get required scope from response
        String scope = WLAuthorizationManager.getInstance().getAuthorizationScope(response);

        //Obtain authorization header for the scope
        WLAuthorizationManager.getInstance().obtainAuthorizationHeader(scope, new WLResponseListener() {

            // This method will be invoked if an authorization header was obtained successfully:
            @Override
            public void onSuccess(WLResponse wlResponse) {

                // Add the obtained authorization header to the original request
                WLAuthorizationManager.getInstance().addCachedAuthorizationHeader(get);
                try {
                    // resend the request
                    HttpResponse response = client.execute(get);

                    // At this point a response from the resource was received, process it:
                    processResponse(response);
                    } catch (Exception e) {
                        Log.e("RESOURCE", "Exception during request");
                    }
                }

                // This method will be invoked if an authorization header was not obtained:
                @Override
                public void onFailure(WLFailResponse response) {
                    Log.e("RESOURCE", "Unable to obtain token");
                }
            });

        } else  {
                    // At this point a response from the resource was received, process it:
                    processResponse(response);
                }
               
        } catch (Exception e) {
            Log.e("RESOURCE", "Exception during request");
        }