[英]AWS Java Lambda Function with API Gateway - POJO input and OutputStream output
我正在 Java 中創建一個簡單的 AWS Lambda Function 並返回一個 ZBCD1B686177659B1DFC1ZFF0403。 function 由 API 網關調用。 輸入是一個簡單的 POJO class,但 output 應該是文件的OutputStream
。
對於輸入,我嘗試創建一個 POJO class 並僅使用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
作為 output。 如何才能做到這一點? 我看到我可以使用RequestStreamHandler
並且 AWS 有一些關於實現它的文檔。 但是,這將迫使我的輸入成為 InputStream,我不確定這將如何與 API 網關一起使用。
如何將此 PDF 服務回請求它的客戶端?
請記住,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));
}
但是,我不相信這真的會更好。 如果您只想返回 PDF 而沒有APIGatewayProxyResponseEvent
,您可以,但現在您必須更新 API 網關才能正確發送Content-Type
Z099FB995346F31C749F6E40DB0F395E3。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.