正在获取HTTP 400:尝试使用Kotlin连接到本地DynamoDB时出现错误请求

lmvvr0a8  于 2023-02-13  发布在  Kotlin
关注(0)|答案(1)|浏览(187)

我正在使用Kotlin和Ktor的AWS Kotlin client libraries。当尝试连接到在Docker中运行的本地DynamoDB示例时,我收到以下错误消息:

DEBUG httpTraceMiddleware - DynamoDB-GetItem-835467a5-aedc-40ab-8c28-b56b625ccbd4/Attempt-1: HttpResponse: 400: Bad Request

我使用的库版本是aws.sdk.kotlin:dynamodb:0.18.0-beta,DynamoDB客户端配置如下所示。

suspend fun getValueForKey(tableNameVal: String, keyName: String, keyVal: String) {

    val keyToGet = mutableMapOf<String, AttributeValue>()
    keyToGet[keyName] = AttributeValue.S(keyVal)

    val request = GetItemRequest {
        key = keyToGet
        tableName = tableNameVal
    }
    val provider = StaticCredentialsProvider.Builder().apply {
        accessKeyId = "fakeMyKeyId"
        secretAccessKey = "fakeSecretAccessKey"
    }.build()

    DynamoDbClient {
        credentialsProvider = provider
        region = "us-east-1"
        endpointUrl = Url.parse("http://localhost:8000")
    }.use { ddb ->
        val returnedItem = ddb.getItem(request)
        val numbersMap = returnedItem.item
        numbersMap?.forEach { entry ->
            println(entry.key)
            println(entry.value)
        }
    }
}

我甚至尝试添加伪访问/密钥based on the official guide,但结果是一样的。因此,即使我不指定credentialsProvider参数,我也会得到同样的错误。在命令行中,我可以使用以下命令成功执行操作:

aws dynamodb get-item \
    --table-name key_values \
    --key '{"key": {"S": "key1"}}' \
    --endpoint-url http://localhost:8000
wgeznvg7

wgeznvg71#

我刚刚发现,我必须创建一个返回静态本地端点的“假”EndpointProvider。跳过credentialsProvider可能会导致CredentialsProviderException,所以值得使用一个具有伪值的CredentialsProviderException。您可以使用任何访问/密钥对。定义一个region是必须的。

val credentials = StaticCredentialsProvider.Builder().apply {
        accessKeyId = "fakeMyKeyId"
        secretAccessKey = "fakeSecretAccessKey"
    }.build()

    val endpoint = EndpointProvider { Endpoint(Url.parse("http://localhost:8000")) }

    DynamoDbClient {
        credentialsProvider = credentials
        region = "us-west-2"
        endpointProvider = endpoint
    }.use { ddb ->
        val returnedItem = ddb.getItem(request)
        val numbersMap = returnedItem.item
        numbersMap?.forEach { entry ->
            println(entry.key)
            println(entry.value)
        }
    }

相关问题