HTTP request source code:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.amazonaws.http.HttpMethodName;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.client.AWSStartupHandler;
import com.amazonaws.mobile.client.AWSStartupResult;
import com.amazonaws.mobile.client.Callback;
import com.amazonaws.mobile.client.results.Tokens;
import com.amazonaws.mobileconnectors.apigateway.ApiClientFactory;
import com.amazonaws.mobileconnectors.apigateway.ApiRequest;
import com.amazonaws.mobileconnectors.apigateway.ApiResponse;
import com.amazonaws.util.IOUtils;
import com.amazonaws.util.StringUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
// TODO Replace this with your api friendly name and client class name
import ProjectTableAPI.ProjectTableAPIClient;



public class Gatewaysensor extends AppCompatActivity {
    private static final String TAG = Gatewaysensor.class.getSimpleName();

    // TODO Replace this with your client class name
    private ProjectTableAPIClient apiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gatewaysensor);

        // Initialize the AWS Mobile Client
        AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
            @Override
            public void onComplete(AWSStartupResult awsStartupResult) {
                Log.d(TAG, "AWSMobileClient is instantiated and you are connected to AWS!");
            }
        }).execute();


        // Create the client
        apiClient = new ApiClientFactory()
                .credentialsProvider(null)
                .build(ProjectTableAPIClient.class);

        doInvokeAPI();
    }



    public void doInvokeAPI(){
        AWSMobileClient.getInstance().getTokens(new Callback<Tokens>() {
            @Override
            public void onResult(Tokens tokens) {
                doInvokeAPI(tokens.getIdToken().getTokenString());
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }


    public void doInvokeAPI(String token) {
// Create components of api request
        final String method = "GET";
        final String path = "/query";

        final String body = "{\n" +
        "\n" +
                "  \"resource\": \"/query\",\n" +
                "\n" +
                "  \"httpMethod\": \"GET\",\n" +
                "\n" +
                "  \"pathParams\": \"{}\",\n" +
                "\n" +
                "  \"queryStringParameters\": {\n" +
                "\n" +
                "    \"userId\": \"Rosie\"\n" +
                "\n" +
                "  },\n" +
                "\n" +
                "  \"payload\": {}\n" +
                "\n" +
                "}";
        final byte[] content = body.getBytes(StringUtils.UTF8);

        final Map parameters = new HashMap<>();
       parameters.put("lang", "en_US");

        final Map headers = new HashMap<>();
        ApiRequest localRequest =
                new ApiRequest(apiClient.getClass().getSimpleName())
                        .withPath(path)
                        .withHttpMethod(HttpMethodName.valueOf(method))
                        .withHeaders(headers)
                        .addHeader("Content-Type","application/json")
                        .addHeader("Authorization", token)              //Use JWT token
                       .withParameters(parameters);
// Only set body if it has content.
        if (body.length() > 0) {
            localRequest = localRequest
                    .addHeader("Content-Length", String.valueOf(content.length))
                    .withBody(content);
        }

        final ApiRequest request = localRequest;

        // Make network call on background thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG,
                            "Invoking API w/ Request : " +
                                    request.getHttpMethod() + ":" +
                                    request.getPath());

                    final ApiResponse response = apiClient.execute(request);

                    final InputStream responseContentStream = response.getContent();

                    if (responseContentStream != null) {
                        final String responseData = IOUtils.toString(responseContentStream);
                        Log.d(TAG, "Response : " + responseData);
                        Log.d(TAG, "Test:");

                    }

                    Log.d(TAG, response.getStatusCode() + " " + response.getStatusText());

                } catch (final Exception exception) {
                    Log.e(TAG, exception.getMessage(), exception);
                    exception.printStackTrace();
                }
            }
        }).start();

    }

   }`

403 Forbidden happen when invoking API Gateway from Android App.

I would like to post/get data to DynamoDB from my Android app. I use REST API and use API GATEWAY + Lambda function (serverless function ) to communicate with DyanmoDB. I follow all the steps from

https://aws-amplify.github.io/docs/android/api#rest-api".

For authorization, I use "Cognito User Pools". My App operation, after user login with Cognito user pool successfully, user able to post/get the data to API GATEWAY. But when I run the app, debug log show 403 forbidden instead of "retrieve data". If possible someone can advise me?

0 Answers