首页 > 解决方案 > 执行失败 Twilio SMS (Java)

问题描述

我正在尝试使用 Twilio 发送 SMS 消息。我已按照所有说明操作并设置了 JAVA_HOME 环境变量。当我运行程序时,我得到:

任务“:StockAlertClass:SMS.main()”执行失败。

进程 'command'/Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/bin/java'' 以非零退出值 1 结束

我的java类是:

import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class SMS {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("HiddenForPrivacy");
    public static final String AUTH_TOKEN = System.getenv("HiddenForPrivacy");

    public static void Message() {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        Message message = Message.creator(new PhoneNumber("+HiddenForPrivacy"),
                new PhoneNumber("HiddenForPrivacy"),
                "Test ").create();

        System.out.println(message.getSid());
    }
    public static void main(String[] args) {
        Message();
    }
}

build.gradle 是:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
    mavenLocal()
}
if (hasProperty('buildScan')) {
    buildScan {
        termsOfServiceUrl = 'https://gradle.com/terms-of-service'
        termsOfServiceAgree = 'yes'
    }
}

dependencies {
    compile 'org.slf4j:slf4j-simple:1.6.+'
    compile 'com.sparkjava:spark-core:2.5.+'
    implementation group: "com.twilio.sdk", name: "twilio", version: "8.21.0"
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
    // https://mvnrepository.com/artifact/com.twilio.sdk/twilio
    runtimeOnly group: 'com.twilio.sdk', name: 'twilio', version: '8.21.0'
}

test {
    useJUnitPlatform()
}

标签: javagradletwilio

解决方案


Twilio 开发人员布道者在这里。

我很关心你是如何分享这些台词的:

    public static final String ACCOUNT_SID = System.getenv("HiddenForPrivacy");
    public static final String AUTH_TOKEN = System.getenv("HiddenForPrivacy");

您不必在这些行中隐藏密钥。相反,您应该将 Account SID 和 Auth Token 设置为调用的环境变量ACCOUNT_SIDAUTH_TOKEN然后您的代码应如下所示:

    public static final String ACCOUNT_SID = System.getenv("ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("AUTH_TOKEN");

如果您在这些调用中使用了实际的 Account Sid 和 Auth Token,那么我的猜测是您的代码失败,因为它们设置不正确。

我建议阅读这篇关于在 Java 中使用环境变量的博客文章以获取更多详细信息。


推荐阅读