【发布时间】:2017-09-27 23:15:40
【问题描述】:
我设置了一个 API Gateway GET 方法,该方法与基本的 AWS Lambda 函数集成。我已经在集成请求上启用了请求正文直通到预设的方法请求直通模板。
我想根据请求的资源路径做不同的事情。例如,如果路径是 /foo,我将解释 foo 请求,或者 /bar 将解释为 bar 请求,使用相同的 Lambda 函数。所以我需要根据 Lambda 函数本身的资源路径进行切换。
我无法访问映射的有效负载模板。根据AWS help,所有数据都应该在那里。但在 java 中,我不知道如何使用 Jackson、org.json 或 json-path 将 API 网关的输入转换为可解析的 json。
这是我的 Lambda 代码。任何有关如何从 API Gateway GET 获取“资源路径”或任何方法请求传递的帮助将不胜感激。
import org.json.JSONObject;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Object, Object> {
@Override
public Object handleRequest(Object input, Context context) {
JSONObject inputJson = new JSONObject(input.toString());
JSONObject contextJson = inputJson.getJSONObject("context");
String resourcePath = contextJson.getString("resource-path");
return resourcePath;
}
}
这是我认为作为输入发送到函数中的内容:
{
"body-json" : {},
"params" : {
"path" : {},
"querystring" : {},
"header" : {}
},
"stage-variables" : {},
"context" : {
"account-id" : "xxxxxxxxx",
"api-id" : "xxxxxxxxx",
"api-key" : "xxxxxxxxx",
"authorizer-principal-id" : "",
"caller" : "xxxxxxxxx",
"cognito-authentication-provider" : "",
"cognito-authentication-type" : "",
"cognito-identity-id" : "",
"cognito-identity-pool-id" : "",
"http-method" : "GET",
"stage" : "test-invoke-stage",
"source-ip" : "test-invoke-source-ip",
"user" : "xxxxxxxxxxxxxxxx",
"user-agent" : "Apache-HttpClient/4.5.x (Java/1.8.0_112)",
"user-arn" : "arn:aws:iam::230537478972:root",
"request-id" : "test-invoke-request",
"resource-id" : "75bakm",
"resource-path" : "/text"
}
}
但我得到了:
{
"errorMessage": "Expected a ':' after a key at 11 [character 12 line 1]",
"errorType": "org.json.JSONException",
"stackTrace": [
"org.json.JSONTokener.syntaxError(JSONTokener.java:433)",
"org.json.JSONObject.<init>(JSONObject.java:216)",
"org.json.JSONObject.<init>(JSONObject.java:323)",
"xxx.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:12)"
]
}
【问题讨论】:
标签: java json amazon-web-services lambda aws-api-gateway