Amazon SNS keep sending message with last string

Viewed 134

Currently i am using Springboot with kotlin to send SMS using AWS SNS to person in Vietnam.
however it keeps sending a message with last string in my message contents.

@Bean
fun snsClient(): AmazonSNS {
    val credentials = BasicAWSCredentials(accessKey, secretKey)
    val snsClient = AmazonSNSClient.builder()
        .withRegion(Regions.AP_SOUTHEAST_1)
        .withCredentials(AWSStaticCredentialsProvider(credentials))
        .build()

    return snsClient
}

private fun sendMsg(snsClient: AmazonSNS, msg: String, phoneNumber: String) {
    try {
        val req = PublishRequest()
        req.message = msg
        req.phoneNumber = phoneNumber

        val res = snsClient.publish(req)
        System.out.println(res.sdkResponseMetadata)
    } catch (e: AmazonSNSException) {
        e.printStackTrace()
    }
}

can anyone help me with this problem?

according to aws documentation, it tells me to use PublishRequest().builder() . but, when i try to use builder() method, there is no builder() method in PublishRequest().

1 Answers

To send a message using Amazon SNS with the AWS SDK for Kotlin, use this code:

package com.kotlin.sns

import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.PublishRequest
import aws.sdk.kotlin.services.sns.model.SnsException
import kotlin.system.exitProcess
  

suspend fun main(args:Array<String>) {

    val usage = """
    
        Usage: 
            <message> <phoneNumber>
        Where:
            message - the message text to send.
            phoneNumber - the mobile phone number to which a message is sent (for example, +1XXX5550100). 
        """

    if (args.size != 2) {
        println(usage)
        exitProcess(0)
    }

    val message = args[0]
    val phoneNumber = args[1]
    val snsClient = SnsClient({ region = "us-east-1" })
    pubTextSMS(snsClient, message, phoneNumber)
    snsClient.close()
}


suspend fun pubTextSMS(snsClient: SnsClient, messageVal: String?, phoneNumberVal: String?) {
    try {
        val request = PublishRequest {
            message = messageVal
            phoneNumber = phoneNumberVal
        }

        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")

    } catch (e: SnsException) {
        println(e.message)
        snsClient.close()
        exitProcess(0)
    }
}

TO learn how to get up and running with the AWS SDK for Kotlin, see Get started with the SDK for Kotlin.

Here are the Amazon SNS Kolin examples:

Amazon SNS Kotlin code examples

Related