簡體   English   中英

How to consume API from AWS API Gateway integrated with Lambda function in Java?

[英]How to consume API from AWS API Gateway integrated with Lambda function in Java?

我正在嘗試在 React 應用程序中使用 API 但我收到此錯誤作為響應。

{errorMessage: "An error occurred during JSON parsing", errorType: "java.lang.RuntimeException", stackTrace: Array(0), cause: {…}}
cause:
cause: {errorMessage: "Can not deserialize instance of java.lang.String o…MemoryAsInputStream@727803de; line: 1, column: 1]", errorType: "com.fasterxml.jackson.databind.JsonMappingException", stackTrace: Array(6)}
errorMessage: "com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token↵ at [Source: lambdainternal.util.NativeMemoryAsInputStream@727803de; line: 1, column: 1]"
errorType: "java.io.UncheckedIOException"

這是從 React 發出的 POST 請求。

    async handleSubmit(event) {
        event.preventDefault();
        const data = "{\"type\":\"select\",\"startdate\":\""+this.state.startdate+"\",\"enddate\":\""+this.state.enddate+"\"}";
        const url = "<API Gateway endpoint>";
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: "{\"type\":\"select\",\"startdate\":\"2020-12-15 09:59:59\",\"enddate\":\"2021-01-13 21:37:43\"}"
        });
        const body = await response.json();
        this.setState({invoices : body, isLoading:false})
        console.log(this.state.invoices);
    }

最有可能的問題是 Java 處理程序方法無法解析請求數據。 我不確定如何構造請求正文,以便 Lambda 處理程序接受請求正文作為輸入參數。

    public static String handleRequest(String input, Context context) {
        Connection conn = createConnection();
        Statement stmt = null;
        JSONObject jsonObject = null;
        <JDBC stuff>
        return jsonObject.toString();
    }

對於 API 網關,我認為 Java 處理程序 class 需要實現 RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent>。 然后你應該能夠從 event.getBody() 中獲取 json 字符串,你可以反序列化 json 字符串或直接解析它。 對於響應,您需要構造 APIGatewayProxyResponseEvent object。

使用 Map<String, String> 作為輸入參數的類型修復了它。 響應正文中的 JSON 被轉換為鍵值對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM