【问题标题】:AWS Java Lambda Function with API Gateway - POJO input and OutputStream output带有 API 网关的 AWS Java Lambda 函数 - POJO 输入和 OutputStream 输出
【发布时间】:2019-11-16 04:37:57
【问题描述】:

我正在用 Java 创建一个简单的 AWS Lambda 函数,它创建并返回一个 PDF。该函数由 API 网关调用。输入是一个简单的 POJO 类,但输出应该是文件的 OutputStream

对于输入,我尝试创建一个 POJO 类并仅使用 APIGatewayProxyRequestEvent 并且工作正常。下面是我使用的一个简单示例,它接受输入并打印回查询字符串参数。

public class LambdaFunctionHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    @Override
    public APIGatewayProxyResponseEvent handleRequest( APIGatewayProxyRequestEvent input, Context context ) {

        return new APIGatewayProxyResponseEvent()
            .withStatusCode(200)
            .withHeaders(Collections.emptyMap())
            .withBody("{\"input\":\"" + input.getQueryStringParameters() + "\"}");
    }

}

效果很好,但现在我需要更改它以使用OutputStream 作为输出。如何才能做到这一点?我看到我可以使用RequestStreamHandler,AWS 有一些documentation 来实现它。但是,这将迫使我的输入成为 InputStream,我不确定这将如何与 API 网关一起使用。

如何将此 PDF 提供给请求它的客户?

【问题讨论】:

  • 不能直接将响应的类型设置为OutputStream(在方法声明和接口中)?

标签: java amazon-web-services aws-lambda


【解决方案1】:

请记住,Lambda 处理程序的 POJO 方法只是为了方便。最终,您可以自己执行此操作并使用 InputStream/OutputStream Lambda 模式。比如:

public void handleRequest(InputStream inputStream,
                          OutputStream outputStream,
                          Context context) throws IOException {
    String inputString = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));

    ObjectMapper objectMapper = new ObjectMapper();
    APIGatewayProxyRequestEvent request = objectMapper.readValue(inputString, APIGatewayProxyRequestEvent.class);

    // do your thing, generate a PDF
    byte[] thePDF = ...
    // create headers
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-type", "application/pdf");

    APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent().
             .withStatusCode(200)
             .withHeaders(headers)
             .withBody(Base64.Encoder.encode(thePDF))
             .withIsBase64Encoded(Boolean.TRUE);

    outputStream.write(objectMapper.writeValueAsString(response)
                                   .getBytes(StandardCharsets.UTF_8));
}

但是,我不相信这真的会更好。如果您只想返回不带 APIGatewayProxyResponseEvent 的 PDF,您可以,但现在您必须更新 API Gateway 以正确发送 Content-Type 标头。

【讨论】:

  • 谢谢,这很有帮助。在响应构建器中,withBody 将只接受一个字符串。所以看来我必须在那里转换它。在 API 网关中,我不得不禁用 Lambda 代理集成。此外,似乎没有发送实际的 PDF,而是发送 JSON 输出。例如,我得到了这个{"statusCode":200,"headers":{"Content-type":"application/pdf"},"body":"[B@59ec2012","isBase64Encoded":true} 我主要只是需要做更多的研究。但现在,我不太清楚如何使用正确的内容类型将二进制数据返回给客户端。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2019-05-02
  • 2020-02-24
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
相关资源
最近更新 更多