问题描述: 在AWS Java Lambda中,无法读取请求体。
解决方法:
确保在Lambda函数的触发器配置中正确设置了请求体。例如,如果使用API Gateway作为触发器,请确保将"Use Lambda Proxy integration"选项设置为"true",并且在API Gateway的请求定义中,将请求体传递给Lambda函数。
确保Lambda函数的输入参数正确解析请求体。在Java Lambda函数中,可以使用以下代码来读取请求体:
public class MyLambdaHandler implements RequestHandler {
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
String requestBody = input.getBody();
// 对请求体进行处理
// ...
}
}
上述代码示例中,input.getBody()
方法可以读取请求体,并将其作为字符串返回。
public class MyLambdaHandler implements RequestHandler {
private ObjectMapper objectMapper = new ObjectMapper();
public APIGatewayProxyResponseEvent handleRequest(MyRequest input, Context context) {
// 对MyRequest对象进行处理
// ...
}
private MyRequest parseRequest(String requestBody) throws IOException {
return objectMapper.readValue(requestBody, MyRequest.class);
}
}
上述代码示例中,parseRequest()
方法使用Jackson库将请求体的JSON字符串反序列化为MyRequest对象。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:region:account-id:api-id/*/*/*"
]
}
]
}
请将region
、account-id
和api-id
替换为相应的值。
通过检查上述步骤,您应该能够解决AWS Java Lambda无法读取请求体的问题。