我需要这个类的帮助,它甚至不返回消息的SID。我的应用程序是24/7全天候运行,它在第一次开始时发送消息,然后它很快就无法发送消息。每次发送邮件时是否需要重新创建TwilioRestClient对象?
public class Twilio {
public static final String ACCOUNT_SID = "VALID SID";
public static final String ACCOUNT_AUTH = "VALID AUTH";
private static Twilio instance;
public static Twilio getInstance() {
return instance == null ? (instance = new Twilio()) : instance;
}
private TwilioRestClient client;
private SmsFactory smsFactory;
private Map<String, String> defaultProps = new HashMap<>();
public Twilio() {
defaultProps.put("From", "VALID TWILIO NUMBER");
client = new TwilioRestClient(ACCOUNT_SID, ACCOUNT_AUTH);
}
public SmsFactory getSMSFactory() {
return smsFactory == null ? (smsFactory = client.getAccount().getSmsFactory()) : smsFactory;
}
private Sms buildSMS(String recipient, String body) {
Sms sms = null;
defaultProps.put("To", recipient);
defaultProps.put("Body", body);
try {
sms = getSMSFactory().create(defaultProps);
} catch (TwilioRestException e) { e.printStackTrace(); }
return sms;
}
public String[] sendSMS(String body, String... recipients) {
List<String> sids = new ArrayList<>();
for (String r : recipients)
sids.add(buildSMS(r, body).getSid());
return sids.toArray(new String[sids.size()]);
}
}
答案 0 :(得分:0)
如果有帮助,您可以尝试使用此代码。它对我来说很好。
public boolean sendSMS(String to, String from, String text){
try {
String[] toarr = to.split(",");
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
if(toarr.length > 0){
for (int i = 0; i < toarr.length; i++) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", toarr[i]));
params.add(new BasicNameValuePair("From", from));
params.add(new BasicNameValuePair("Body", text));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
com.twilio.sdk.resource.instance.Message message = messageFactory.create(params);
}
}
}
catch (TwilioRestException tex) {
tex.printStackTrace();
}
return true;
}