AWS - 使用 @connections websocket 回调 url 从后端发送响应(单向) - API Gateway websocket 协议

Raj*_*Rao 6 java amazon-web-services websocket api-gateway

我一直在努力通过aws提供的回调url(https://******.execute-api.us-east-1.amazonaws.com/test/@connections)向连接的客户端发送响应。

在我的后端中有以下代码来发送响应,这是一种单向通信。

    AwsClientBuilder.EndpointConfiguration config =
            new AwsClientBuilder.EndpointConfiguration("https://*********.execute-api.us-east-1.amazonaws.com/test", "us-east-1");
    AmazonApiGatewayManagementApi client = AmazonApiGatewayManagementApiClientBuilder.standard()
            .withEndpointConfiguration(config).build();


    PostToConnectionRequest request = new PostToConnectionRequest();
    request.withConnectionId("bGYcWek5oAMCKwA=");
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    ByteBuffer buff = null;
    try {
        buff = encoder.encode(CharBuffer.wrap("Hello from lambda"));
    } catch (CharacterCodingException e) {
        log.error("Error while encoding", e);
    }
    request.withData(buff);
    PostToConnectionResult result = client.postToConnection(request);
    log.info("Result of websocket send:\n" + result);
Run Code Online (Sandbox Code Playgroud)

获取服务:AmazonApiGatewayManagementApi;状态代码:403;错误代码:InvalidSignatureException异常。

注意:我已经设置了所有内容,例如证书和 aws 访问密钥。

正如 aws 文档中提到的,我尝试过使用awscurl,它有效。我可以在 websocket 连接的客户端上看到响应。 https://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html

小智 2

您需要提供您的AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY表格BasicAWSCredentials

BasicAWSCredentials awsCreds = new BasicAWSCredentials("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY");
AmazonApiGatewayManagementApi client = AmazonApiGatewayManagementApiClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withEndpointConfiguration(config).build();
Run Code Online (Sandbox Code Playgroud)