Skip to content

Instantly share code, notes, and snippets.

@cnicodeme
Last active December 26, 2015 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cnicodeme/7150959 to your computer and use it in GitHub Desktop.
Save cnicodeme/7150959 to your computer and use it in GitHub Desktop.
Easily send an SMS using the Twilio API
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class Twilio {
// The following variables are needed to use the Twilio API.
// Instead of hard writing them in this code, I use the application.conf configuration file.
private final static String messageUrl = play.Play.application().configuration().getString("twilio.url"); // https://api.twilio.com/2010-04-01/Accounts/{your_auth_key}/Messages.json
private final static String authKey = play.Play.application().configuration().getString("twilio.auth_key"); // {your_auth_key}
private final static String authToken = play.Play.application().configuration().getString("twilio.auth_token"); // {your_auth_token}
private final static String from = play.Play.application().configuration().getString("twilio.from"); // {your_twilio_phone_number}
public static void sendSms(String to, String body) throws UnsupportedEncodingException, ClientProtocolException, IOException {
if ((to == null || to.isEmpty()) || (body == null || body.isEmpty())) {
throw new NullPointerException("Unable to send message, to or body empty.");
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(messageUrl);
httppost.addHeader (BasicScheme.authenticate (new UsernamePasswordCredentials (authKey, authToken), "UTF-8", false));
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("From", from));
params.add(new BasicNameValuePair("To", to));
params.add(new BasicNameValuePair("Body", body));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// Execute and get the response.
httpclient.execute(httppost);
}
}
Copy link

ghost commented Mar 31, 2015

its showing an error:package play doesnt exist..Please give me a link to download that package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment