I am trying to send a sms using twillio, here the code:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import org.apache.http.NameValuePair;
import org.apache.http.auth.Credentials;
import org.apache.http.message.BasicNameValuePair;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
public class SendSms extends HttpServlet {
private Logger logger = Logger.getLogger(SendSms.class.getName());
private TwilioRestClient client;
private Credentials credentials;
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
final String twilioAccountSid = System.getenv("TWILIO_ACCOUNT_SID");
final String twilioAuthToken = System.getenv("TWILIO_AUTH_TOKEN");
final String twilioNumber = System.getenv("TWILIO_NUMBER");
final String toNumber = (String) twilioNumber;
String message = "prova";
client = new TwilioRestClient(twilioAccountSid, twilioAuthToken);
sendMessage(toNumber, message);
}
public void sendMessage(String to, String message) {
List<NameValuePair> params = getParams(to, message);
try {
this.client.getAccount().getMessageFactory().create(params);
} catch (TwilioRestException exception) {
exception.printStackTrace();
}
}
private List<NameValuePair> getParams(String to, String message) {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("Body", message));
params.add(new BasicNameValuePair("To", to));
params.add(new BasicNameValuePair("From", to));
return params;
}
}
Is just a test so I don’t matter about performarce, code cleaning and so on. Calling the servlet I am getting the following error:
WARNING: Error for /SendSms
java.lang.NoClassDefFoundError: com/twilio/sdk/TwilioRestException
I am using maven, importing the related twillio apis, here the pom dependency:
<dependencies>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio-java-sdk</artifactId>
<version>(6.0,6.9)</version>
</dependency>
Does someone has some suggestions?
Thank you in advance.
2
Answers
Perhaps the missing
<scope>
forcompile
is the problem:And for the full detailed instructions regarding the dev environment:
https://www.twilio.com/docs/quickstart/java/devenvironment#pomxml
I have a tired application layered like this
WebServices
Services
DAO
Common
I call twilio in the services module, so I put the maven dependency in the pom file in that maven module. For some reason I kept getting the same error as you. Adding the dependency to the WebServices module fixed the issue