在Java 中 使用 AWS SNS 来发送短信的例子
生活随笔
收集整理的這篇文章主要介紹了
在Java 中 使用 AWS SNS 来发送短信的例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:AWS Java SDK 地址
1)AWS java SDK 主頁在?https://aws.amazon.com/tr/sdk-for-java/?nc1=h_ls
2)AWS 所有的Java SDK 的,maven倉庫地址在:https://mvnrepository.com/artifact/com.amazonaws
下面是本例的信息:
1)首先:下載必要的AWS 開發包,如下所示:
?如果你用maven來構建,則直接可以在pom.xml加入以下的配置就可以了
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-sns --> <dependency><groupId>com.amazonaws</groupId><artifactId>aws-java-sdk-sns</artifactId><version>1.11.229</version> </dependency>AWS SNS 地址在:https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-sns
?
Java代碼如下
import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.amazonaws.services.sns.model.MessageAttributeValue; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.services.sns.model.PublishResult;import java.util.HashMap; import java.util.Map;public class ShortMessage {private Map<String, MessageAttributeValue> smsAttributes;public Map<String, MessageAttributeValue> getDefaultSMSAttributes() {if (smsAttributes == null) {smsAttributes = new HashMap<>();smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue().withStringValue("1").withDataType("String"));smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue().withStringValue("0.05").withDataType("Number"));smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue().withStringValue("Transactional").withDataType("String"));}return smsAttributes;}public PublishResult sendSMSMessage(String phoneNumber, String message) {return sendSMSMessage(phoneNumber, message, getDefaultSMSAttributes());}public PublishResult sendSMSMessage(String phoneNumber, String message, Map<String, MessageAttributeValue> smsAttributes) {AWSCredentials awsCredentials = new AWSCredentials() {@Overridepublic String getAWSAccessKeyId() {return "xxxxxxxx"; // 帶有發短信權限的 IAM 的 ACCESS_KEY}@Overridepublic String getAWSSecretKey() {return "xxxxxxxx"; // 帶有發短信權限的 IAM 的 SECRET_KEY}};AWSCredentialsProvider provider = new AWSCredentialsProvider() {@Overridepublic AWSCredentials getCredentials() {return awsCredentials;}@Overridepublic void refresh() {}};AmazonSNS amazonSNS = null;try {amazonSNS = AmazonSNSClientBuilder.standard().withCredentials(provider).withRegion("us-east-1").build();} catch (Exception e) {}return amazonSNS.publish(new PublishRequest().withMessage(message).withPhoneNumber(phoneNumber).withMessageAttributes(smsAttributes));}public static void main(String[] args) {ShortMessage shortMessage = new ShortMessage();PublishResult publishResult = shortMessage.sendSMSMessage("+8613911088332", "trial SMS msg");System.out.println(publishResult);}}?
總結
以上是生活随笔為你收集整理的在Java 中 使用 AWS SNS 来发送短信的例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js 实时监听input中值变化
- 下一篇: java.lang.NoSuchMeth