如何使用aws api网关在android中调用GET方法?

时间:2016-12-27 20:56:19

标签: android amazon-web-services android-studio aws-sdk aws-api-gateway

所以我有这个lambda函数,只需输入一个用户名作为输入,然后转到dynamoDB并抓取该表中具有所有属性的相应用户并将其记录下来。当我在lambda中测试时,它工作得很好。但是,当我通过sdk调用GET方法时,它不起作用,我不明白为什么?

这是lambda中的那个函数。

AWS.config.update(dynamoDBConfiguration);

var dynamodb = new AWS.DynamoDB.DocumentClient(); 
exports.handler = function(event, context, callback) 
{
    console.log('entered exports handler');
    console.log(JSON.stringify(event, null, '  '));

    var userTableName = "usersTable";

    var params = {
        TableName : userTableName,
        Key: {
            "username": event.username
        }
        // AttributesToGet: [
        // 'STRING_VALUE',
        //  /* more items */
        // ],
    };
    dynamodb.get(params, function(err, data)
        { if (err) {
                console.log(err);
                callback(err);
            } else {
                console.log('great success: %j',data);
                callback(null, data);
            }
        });
};

现在我试图在API getway中测试这个功能,这样我以后可以部署sdk,但是我很难解决这个问题,并希望你们可以帮助我摆脱我的缺失!

这是我的api中的GET方法 enter image description here

接下来,我的方法请求。 enter image description here

我的整合请求 enter image description here

我的方法回复

enter image description here

后跟我的输出模型

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "username": {"type":"string"}
    },
    "title": "Output"
}

我的整合响应 enter image description here

这是我在Lambda中测试时获得的输出(因此工作正常)。

{
  "Item": {
    "experience": "0",
    "displayName": "Archer",
    "profileImageRef": "default",
    "folders": {
      "My Cards": {
        "cards": {},
        "name": "My Cards"
      }
    },
    "birthdate": "1/1/1990",
    "lastName": "Farooqui",
    "username": "Archer",
    "email": "qteen1@gmail.com",
    "firstName": "Qamar"
  }
}

在android中,这是我生成的sdk放入我的android工作室。

MyUserClient sdk

@com.amazonaws.mobileconnectors.apigateway.annotation.Service(endpoint = "https://ow2zhiry2b.execute-api.us-west-2.amazonaws.com/awsTest")

    public interface MyUserClient {


        /**
         * A generic invoker to invoke any API Gateway endpoint.
         * @param request
         * @return ApiResponse
         */
        com.amazonaws.mobileconnectors.apigateway.ApiResponse execute(com.amazonaws.mobileconnectors.apigateway.ApiRequest request);

        /**
         * 
         * 
         * @param username 
         * @return Output
         */
        @com.amazonaws.mobileconnectors.apigateway.annotation.Operation(path = "/", method = "GET")
        Output rootGet(
                @com.amazonaws.mobileconnectors.apigateway.annotation.Parameter(name = "username", location = "query")
                String username);
    }

这是我的输出类,也是从sdk

生成的
public class Output {
    @com.google.gson.annotations.SerializedName("username")
    private String username = null;

    /**
     * Gets username
     *
     * @return username
     **/
    public String getUsername() {
        return username;
    }

    /**
     * Sets the value of username.
     *
     * @param username the new value
     */
    public void setUsername(String username) {
        this.username = username;
    }

}

最后,我尝试在异步任务中实现GEt方法,但它一直在崩溃日志声明。

class gateWayAsyncTask extends AsyncTask<Void, Void, Void>
    {
        private String userName;
        public gateWayAsyncTask(String userName)
        {
            this.userName = userName;
        }
        @Override
        protected Void doInBackground(Void... params)
        {
            creatingUser = clientFactory.build(com.awsTest.clientsdk.MyUserClient.class);
            userName = creatingUser.rootGet("Archer").getUsername();
            return null;
            //clientFactory, and creatingUser variables are assigned in the parent class of this Async task don't worry.
        }
        @Override
        public void onPostExecute(Void var)
        {
            Log.d("gateway","gateway succeded!");
            Log.d("gateway",userName);
            Toast.makeText(getBaseContext(),userName,Toast.LENGTH_LONG).show();
        }
    }

这是我的stackTrace

12-27 12:42:48.929 29019-29019/com.daprlabs.aaron.swipedeck2 E/UncaughtException: java.lang.NullPointerException: println needs a message
                                                                                      at android.util.Log.println_native(Native Method)
                                                                                      at android.util.Log.d(Log.java:139)
                                                                                      at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:313)
                                                                                      at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:281)
                                                                                      at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                      at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5525)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
12-27 12:42:49.169 29019-29019/com.daprlabs.aaron.swipedeck2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.daprlabs.aaron.swipedeck2, PID: 29019
                                                                               java.lang.NullPointerException: println needs a message
                                                                                   at android.util.Log.println_native(Native Method)
                                                                                   at android.util.Log.d(Log.java:139)
                                                                                   at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:313)
                                                                                   at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:281)
                                                                                   at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                   at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5525)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
12-27 12:43:14.387 29295-29295/com.daprlabs.aaron.swipedeck2 D/gateway: gateway succeded!
12-27 12:43:14.388 29295-29295/com.daprlabs.aaron.swipedeck2 E/UncaughtException: java.lang.NullPointerException: println needs a message
                                                                                      at android.util.Log.println_native(Native Method)
                                                                                      at android.util.Log.d(Log.java:139)
                                                                                      at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:313)
                                                                                      at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:281)
                                                                                      at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                      at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5525)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
12-27 12:43:14.604 29295-29295/com.daprlabs.aaron.swipedeck2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.daprlabs.aaron.swipedeck2, PID: 29295
                                                                               java.lang.NullPointerException: println needs a message
                                                                                   at android.util.Log.println_native(Native Method)
                                                                                   at android.util.Log.d(Log.java:139)
                                                                                   at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:313)
                                                                                   at com.daprlabs.aaron.zivitApp.Cognito.LogInZivit$gateWayAsyncTask.onPostExecute(LogInZivit.java:281)
                                                                                   at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                   at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5525)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

更新

所以当我看着云表时。它确实表明我的lambda函数正在被调用和执行。但是,我没有得到回报价值。所以我的方法响应和/或集成响应有问题,但我不确定是什么。

2 个答案:

答案 0 :(得分:1)

看起来整合响应中的模板为空,Lambda输出与输出模型不匹配。在集成响应页面的Body Mapping Templates下,选择左侧的application / json。在右侧,输入如下模板体:


    {
        "username": $input.json('$.username')
    }

另外,尝试通过API Gateway控制台上的test execute测试API Gateway GET方法。如果您仍然遇到问题,请发布测试调用的“日志”输出。

答案 1 :(得分:1)

所以我解决了这个问题。感谢:AWS的@MikeD

如果有人想要离开  ANDROID - &gt; API GATEWAY - &gt; LAMBDA功能(终点,返回值) - &gt; API GATEWAY - &gt;机器人。

  1. 确保您的lambda函数返回一些内容(字符串或数字)。
  2. 所以这是一个简单的计算器lambda函数:

    console.log('Loading the Calc function');
    
    exports.handler = function(event, context) {
        console.log('Received event:', JSON.stringify(event, null, 2));
        if (event.a === undefined || event.b === undefined || event.op === undefined) {
            context.fail("400 Invalid Input");
        }
        var res = {};
        res.a = Number(event.a);
        res.b = Number(event.b);
        res.op = event.op;
    
        if (isNaN(event.a) || isNaN(event.b)) {
            context.fail("400 Invalid Operand");
        }
    
        switch(event.op)
        {
            case "+":
            case "add":
                res.c = res.a + res.b;
                console.log('WORKED FROM ANDROID!');
                break;
            case "-":
            case "sub":
                res.c = res.a - res.b;
                break;
            case "*":
            case "mul":
                res.c = res.a * res.b;
                break;
            case "/":
            case "div":
                res.c = res.b===0 ? NaN : Number(event.a) / Number(event.b);
                break;
            default:
                context.fail("400 Invalid Operator");
                break;
        }
        context.succeed(res);
    };
    

    请注意,我返回的变量名称为res。其中包含3个数字a,b和c。

    现在,如果你要从Lambda回来 - &gt; API网关 - &gt; Android系统。在集成响应中,在body映射模板中,在application / json中,我有以下模板:

    #set($allParams = $input.params())
    {
        "c" : $input.json('$.c')
    
    
    }
    

    接下来,在您的方法响应中。确保创建模型(如果单击&#34; models&#34;),可以在左侧窗格中为方法创建模型以进行方法响应并进行设置。这是我的输出模型:

    {
        "$schema": "http://json-schema.org/draft-04/schema#",
        "type": "object",
        "properties": {
            "c": {"type":"string"}
        },
        "title": "Output"
    }
    

    我把这个模型放在方法响应中(重复)。并注意我在我的模型中(在方法响应中)和我的集成响应中的身体映射模板中如何同时拥有c。如果您愿意,可以输入"c": {"type":"number"}

    然后当你部署api时。它应该工作(如果您的错误来自路径:Lambda - &gt; Api网关 - &gt; Android)。