【问题标题】:How to consume API from AWS API Gateway integrated with Lambda function in Java?如何使用与 Java 中的 Lambda 函数集成的 AWS API Gateway 中的 API?
【发布时间】:2021-05-31 20:36:33
【问题描述】:

我正在尝试在 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();
    }

【问题讨论】:

  • 您是否使用 LAMBDA 或 LAMBDA_PROXY 与 Api Gateway 集成?
  • 我正在使用 LAMBDA 集成

标签: java reactjs lambda aws-lambda aws-api-gateway


【解决方案1】:

对于 API Gateway,我认为 Java 处理程序类需要实现 RequestHandler。 然后你应该可以从 event.getBody() 中获取 json 字符串,你可以反序列化 json 字符串,也可以直接解析它。对于响应,您需要构造 APIGatewayProxyResponseEvent 对象。

【讨论】:

    【解决方案2】:

    修复了它使用 Map 作为输入参数的类型。 响应正文中的 JSON 被转换为键值对。

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2019-07-09
      • 1970-01-01
      • 2019-06-22
      • 2020-11-20
      • 2017-04-18
      • 2017-02-08
      • 2021-02-08
      • 2021-08-01
      相关资源
      最近更新 更多