0

How to send sms using Twillio Api in Android. Here is my code. What I don't know is how to set http request body. When I test it using CocoaRestClient(a tool for api test), it is working well. Help me please.

public void sendInviteSMS(String kToNumber) {

    int random4Num = generateRequestCode();

    ...

    String kTwilioSID = "...";
    String kTwilioSecret = "...";
    String kFromNumber = "...";

    String message = String.format("%s has sent you a invite. To accept, enter the following code: %d.", AppUtil.sharedObject().userFirstName, random4Num);
    String kMessage = message;

    String urlString = String.format("https://%s:%s@api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID);

    HashMap postData = new HashMap();
    postData.put("From", kFromNumber);
    postData.put("To", kToNumber);
    postData.put("Body", kMessage);

    // Validate user with the POST call
    AsyncTask doPost = new TwilioPost(urlString) {
        @Override
        protected void onPostExecute(String result) {
            Log.v("PHONE", result);
        }
    }.execute(postData);
}

...

public class TwilioPost extends AsyncTask<HashMap<String, String>, Void, String> {

private String remoteURL;
private static final String TAG = "Wayjer";

public TwilioPost(String remoteURL) {
    this.remoteURL = remoteURL;
}

////////////////////////////////////////////
// Call "doPost" in the background thread
///////////////////////////////////////////
@Override
protected String doInBackground(HashMap<String, String>... hashMaps) {
    try {
        return doPost(hashMaps[0]);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

///////////////////////////////////////////////////////
// Override to convert result string to a JSONObject
//////////////////////////////////////////////////////
@Override
protected void onPostExecute(String result) {
    try {
        Log.v(TAG, result);
    } catch (Exception e) {
        Log.v(TAG, e.toString());
    }
}

public String doPost(HashMap<String, String> postData) throws IOException {
    URL url = new URL(remoteURL);
    String response = "";

    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setReadTimeout(15000);
        connection.setConnectTimeout(15000);

        connection.setRequestMethod("POST");

        String postString = buildString(postData);
        byte[] postBytes = postString.getBytes("UTF-8");

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
        // Write parameter...
        OutputStream outStream = connection.getOutputStream();
        outStream.write(postBytes);
        outStream.flush();
        outStream.close();

        connection.connect();
        int resCode = connection.getResponseCode();
        Log.v(TAG, "Response Message: " + connection.getResponseMessage());

        if (resCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                response += line;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}

private String buildString(HashMap<String, String> postData) throws UnsupportedEncodingException {
    StringBuilder strBuilder = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : postData.entrySet()) {
        try {
            Log.v(TAG, "HTTPPOST ENTRY: " + entry.getKey() + " - " + entry.getValue());
            if (first)
                first = false;
            else
                strBuilder.append("&");

            strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            strBuilder.append("=");
            strBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        } catch (Exception e) {

        }
    }

    return strBuilder.toString();
}

}

William G.
  • 393
  • 2
  • 6
  • 11

1 Answers1

0

Megan from Twilio here.

Interacting with the Twilio REST API directly from your mobile app is not recommended.

When sending SMS from Android, I would suggest that you have a server component using your language of choice. This allows you to keep your API credentials a secret.

Your mobile app would then connect to your server to make the request for sending SMS via the REST API with the parameters of the From, To and Body of the message:

https://www.twilio.com/docs/api/rest/sending-messages

In Java:

// You may want to be more specific in your imports 
import java.util.*; 
import com.twilio.sdk.*; 
import com.twilio.sdk.resource.factory.*; 
import com.twilio.sdk.resource.instance.*; 
import com.twilio.sdk.resource.list.*; 

public class TwilioTest { 
 // Find your Account Sid and Token at twilio.com/user/account 
 public static final String ACCOUNT_SID = "YOUR_ACCOUNT_SID"; 
 public static final String AUTH_TOKEN = "[AuthToken]"; 

 public static void main(String[]args) throws TwilioRestException { 
  TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN); 

   // Build the parameters 
   List<NameValuePair> params = new ArrayList<NameValuePair>(); 
   params.add(new BasicNameValuePair("To", "+16518675309")); 
   params.add(new BasicNameValuePair("From", "+14158141829")); 
   params.add(new BasicNameValuePair("Body", "Hey Jenny! Good luck on the bar exam!")); 
   params.add(new BasicNameValuePair("MediaUrl", "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg"));  

   MessageFactory messageFactory = client.getAccount().getMessageFactory(); 
   Message message = messageFactory.create(params); 
   System.out.println(message.getSid()); 
 } 
}

Please let me know if this helps!

If you can otherwise provide an example error message you may be receiving with your code, I can take a closer look.

Megan Speir
  • 3,745
  • 1
  • 15
  • 25
  • Thank you for your answer. But this is not working for me. It gives me many errors. Sorry. If you think i used wrong library, could you please give me the url of jar file? – William G. Mar 31 '16 at 12:30
  • Hi William,If you are not concerned about the security risk, the workaround would be to modify the twilio-java code to remove the dependency on the erroring components and then rebuild the .jar files. Unfortunately, I do not have the jar file to provide. There is some previous discussion about this incompatibility on Github: https://github.com/twilio/twilio-java/search?q=android&type=Issues – Megan Speir Mar 31 '16 at 17:15