11

In my android application I have created one button, when I had pressed on the button I want to send message.So for that I have created one java class and written twilio code.

final TwilioRestClient client = new TwilioRestClient(
                        ACCOUNT_SID, AUTH_TOKEN);

                // Get the main account (The one we used to authenticate the
                // client)
                final Account mainAccount = client.getAccount();

                final SmsFactory messageFactory = mainAccount.getSmsFactory();
                final Map<String, String> messageParams = new HashMap<String, String>();
                messageParams.put("To", "+912342423423");
                messageParams.put("From", "+132432432434");
                messageParams.put("Body", "This is my message");
                try {
                    messageFactory.create(messageParams);
                } catch (TwilioRestException e) {
                    e.printStackTrace();
                }

when I am using the above code it showing some error like java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager

I have added only one jar file in lib folder as " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".

please tell me what can I do?

Hanuman
  • 958
  • 13
  • 35

6 Answers6

10

I have used HttpPost method to send sms in that i have passed my url with base authentication here is my code

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(
                            "https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/SMS/Messages");
        String base64EncodedCredentials = "Basic "
                            + Base64.encodeToString(
                                    (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
                                    Base64.NO_WRAP);

                    httppost.setHeader("Authorization",
                            base64EncodedCredentials);
                    try {

                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("From",
                                "+123424353534"));
                        nameValuePairs.add(new BasicNameValuePair("To",
                                "+914342423434"));
                        nameValuePairs.add(new BasicNameValuePair("Body",
                                "Welcome to Twilio"));

                        httppost.setEntity(new UrlEncodedFormEntity(
                                nameValuePairs));

                        // Execute HTTP Post Request
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        System.out.println("Entity post is: "
                                + EntityUtils.toString(entity));


                    } catch (ClientProtocolException e) {

                    } catch (IOException e) {

                    }
                }

It is working well.

Megan Speir
  • 3,745
  • 1
  • 15
  • 25
Hanuman
  • 958
  • 13
  • 35
  • I have used your code to send SMS in my own number but response is always like "+15005550006Sent from your Twilio trial account - Welcome to Twilioqueuedoutbound-api2010-04-01USD" But I didnt get the SMS. Please why this happen ? I am using test credentials. – Hitesh Bhalala Dec 16 '15 at 06:08
  • yes status is queued, so it will come after sometime, when I am testing my app at that time also, I got same response. – Hanuman Dec 29 '15 at 11:15
  • having Illegal character at "https://api.twilio.com/2010-04-01/Accounts/{my-_ACCOUNT_SID}/SMS/Messages"); line? – Samir Jan 19 '17 at 12:38
7

This solution with Retrofit

public static final String ACCOUNT_SID = "accountSId";
public static final String AUTH_TOKEN = "authToken";

private void sendMessage() {
    String body = "Hello test";
    String from = "+...";
    String to = "+...";

    String base64EncodedCredentials = "Basic " + Base64.encodeToString(
            (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP
    );

    Map<String, String> data = new HashMap<>();
    data.put("From", from);
    data.put("To", to);
    data.put("Body", body);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.twilio.com/2010-04-01/")
            .build();
    TwilioApi api = retrofit.create(TwilioApi.class);

    api.sendMessage(ACCOUNT_SID, base64EncodedCredentials, data).enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) Log.d("TAG", "onResponse->success");
            else Log.d("TAG", "onResponse->failure");
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("TAG", "onFailure");
        }
    });
}

interface TwilioApi {
    @FormUrlEncoded
    @POST("Accounts/{ACCOUNT_SID}/SMS/Messages")
    Call<ResponseBody> sendMessage(
            @Path("ACCOUNT_SID") String accountSId,
            @Header("Authorization") String signature,
            @FieldMap Map<String, String> metadata
    );
}

Dependencies for build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'

TarikW
  • 359
  • 4
  • 12
  • ResponseBody inside new Callback() giving error – Samir Jan 19 '17 at 12:28
  • The API url no longer wants the /SMS part of the path. You can cut that part out, as seen here: https://www.twilio.com/console/dev-tools/api-explorer/sms/messages/create – JTE Jul 06 '17 at 17:12
7

My method, using OkHttp:

1. Prerequisites

Gradle:

dependencies {    
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
}

Manifest:

<uses-permission android:name="android.permission.INTERNET"/>

Permission in activity:

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build() );
}

2. Code

private void sendSms(String toPhoneNumber, String message){
    OkHttpClient client = new OkHttpClient();
    String url = "https://api.twilio.com/2010-04-01/Accounts/"+ACCOUNT_SID+"/SMS/Messages";
    String base64EncodedCredentials = "Basic " + Base64.encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);

    RequestBody body = new FormBody.Builder()
            .add("From", fromPhoneNumber)
            .add("To", toPhoneNumber)
            .add("Body", message)
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .header("Authorization", base64EncodedCredentials)
            .build();
    try {
        Response response = client.newCall(request).execute();
        Log.d(TAG, "sendSms: "+ response.body().string());
    } catch (IOException e) { e.printStackTrace(); }

}

I used Allu code for generathing authorization in header

thorin86
  • 604
  • 11
  • 26
0

Twilio Java SDK has third party dependencies without them it is not going to work. The dependencies are: 1. Httpcore 2. Httpclient 3. Commons lang 4. Json simple 5. Jackson Not quite sure if you need them all, but at least now you are missing httpcore

Babl
  • 7,446
  • 26
  • 37
  • If i have added those "httpcore or httpclient jar" files then it is showing the error is "Multiple dex files define Lorg/apache/http/ConnectionClosedException;" means same classes or same packages are avialble in twilio-sdk-java jar file.So it is showing duplicate classes is available – Hanuman Jan 27 '15 at 04:28
  • The twilio-sdk-java jar does not have this class, the class which you have mention only available in httpcore.jar, so maybe you have more then one version of httpcore available ? – Babl Jan 27 '15 at 13:17
  • I have added those jar files like "twilio-java-sdk-3.3.10.jar,httpcore.jar,httpclient-4.3.jar" and the class "org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager" present in httpclient-4.3.jar but it is showing the same error the Log-cat is displaying like this – Hanuman Jan 27 '15 at 13:46
  • unable to resolve direct method 13784: Lorg/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager; replacing opcode 0x70 at 0x0024 DexOpt: unable to opt direct call 0x3250 at 0x2e in Lcom/twilio/sdk/TwilioRestClient; Shutting down VM thread exiting with uncaught exception (group=0x430d4140) FATAL EXCEPTION: main Process: com.example.simplesmstest, java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager. at com.twilio.sdk.TwilioRestClient.(TwilioRestClient.java:137) at com.twilio.sdk.TwilioRestClient.(TwilioRestClient.java:108) – Hanuman Jan 27 '15 at 13:50
  • Please tell me where i can find the brief description to get Twilio in my android application,i am very confusing about twilio. – Hanuman Jan 27 '15 at 13:54
0

You should use the BasicPhone project of Twilio SDK. I've tried this to call and now I can call too. This project has all the methods and functions that you need to call and to send SMS. First of all, you need a PHP web service to get capability token and pass that PHP script into your app.

Flexo
  • 87,323
  • 22
  • 191
  • 272
Anshul Tyagi
  • 446
  • 3
  • 24
0

This is how I solved my need. public class TwilioAsyncTask extends AsyncTask {

        Context context;
        ProgressDialog progressDialog;


        public TwilioAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... strings) {

            //
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(
                    "https://api.twilio.com/2010-04-01/Accounts/AC_yourACCOUNT_SID_9b/SMS/Messages");
            String base64EncodedCredentials = "Basic "
                    + Base64.encodeToString(
                    (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
                    Base64.NO_WRAP);

            httppost.setHeader("Authorization",
                    base64EncodedCredentials);
            try {

                int randomPIN = (int) (Math.random() * 9000) + 1000;
                String randomVeriValue = "" + randomPIN;
// these are for control in other anctivity used sharepreference 
                editorTwilio.putString("twilio_veri_no", randomVeriValue);
                editorTwilio.commit();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("From",
                        "+148******")); // what number they gave you
                nameValuePairs.add(new BasicNameValuePair("To",
                        "+90" + phoneNo)); // your phone or our customers
                nameValuePairs.add(new BasicNameValuePair("Body",
                        "Your verification number is : " + randomVeriValue));

                httppost.setEntity(new UrlEncodedFormEntity(
                        nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                System.out.println("Entity post is: "
                        + EntityUtils.toString(entity));
                // Util.showMessage(mParentAct, "Welcome");


            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }

            //
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            // execution of result of Long time consuming operation
            //progressDialog.dismiss();
        }


        @Override
        protected void onPreExecute() {

            progressDialog = ProgressDialog.show(context, "", " Wait for ");

        }


        @Override
        protected void onProgressUpdate(String... text) {
            // Things to be done while execution of long running operation is in
            // progress. For example updating ProgessDialog
        }

    }


    And call your Task


TwilioAsyncTask task = new TwilioAsyncTask(CountryAndPhone.this);
                        task.execute();
Samir
  • 6,405
  • 5
  • 39
  • 42