Aws Lambda:如何在Java中实现的lambda函数中从Api Gateway获取查询参数

时间:2017-09-26 11:34:00

标签: java aws-lambda aws-api-gateway

Aws Lambda - 如何在Java中实现的lambda函数中从Api Gateway获取查询参数。

我有以下代码段:

package com.amazonaws.lambda.demo;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class LambdaFunctionHandler implements RequestHandler<String, String> {

    @Override
    public String handleRequest(String input, Context context) {
        context.getLogger().log("Input: " + input);

        // TODO: implement your handler
        return "Hello from " + input;
    }
}

如果在上面的handleRequest函数中有任何查询参数,我该如何访问。

3 个答案:

答案 0 :(得分:3)

pom.xml 中,确保在此处指定“ 2.2.5 ”或更高版本

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-lambda-java-events</artifactId>
  <version>2.2.5</version>
</dependency>

您的Java lambda类:

import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;

public class LambdaFunctionHandler
    implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input,
            Context context) {
        Map<String, String> inputParams = input.getPathParameters();

        APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
        responseEvent.setBody("body text");
        responseEvent.setStatusCode(200);
        return responseEvent;
    }
}

答案 1 :(得分:0)

您可以尝试在API网关的集成请求正文映射模板中映射所需的所有内容。一旦你构造了体映射模板,那么在lambda的上下文中你将得到你构造的excate json。

请找到以下链接,我已经为类似问题提供了解决方案,

https://stackoverflow.com/a/46407780/7666972

答案 2 :(得分:0)

根据上面 tgk23 的回答,我相信您正在寻找查询参数,而不是路径参数:

public class LambdaFunctionHandler
        implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
        Map<String, String> inputParams = input.getQueryStringParameters();
        for (Map.Entry<String, String> entry : inputParams.entrySet()) {
            LOGGER.info("param: " + entry.getKey() + "=" + entry.getValue());
        }

        APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
        responseEvent.setBody("body text");
        responseEvent.setStatusCode(200);
        return responseEvent;
    }
}