Как отправить SMS с помощью Twilio в моем приложении для android?

В моем android-приложении я создал одну кнопку, когда я нажал на кнопку, Я хочу отправить сообщение.Для этого я создал один класс java и написал код twilio.

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();
                }

когда я использую приведенный выше код, он показывает некоторую ошибку, например java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager

я добавил только один файл Jar в папку lib как " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".

пожалуйста, скажи мне, что я могу сделать?

6 ответов


я использовал метод HttpPost для отправить sms в том, что я передал свой url с базовой аутентификацией вот мой код

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) {

                    }
                }

он работает хорошо.


Это решение с модифицированной

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
    );
}

зависимости build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'


мой метод, используя OkHttp:

1. Предпосылки

Gradle:

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

Манифест:

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

разрешение в деятельности:

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

2. Код

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(); }

}

я использовал код Allu для авторизации generathing в заголовке


Twilio Java SDK имеет сторонние зависимости без них он не будет работать. Зависимости: 1. Httpcore 2. С помощью HttpClient 3. Commons lang 4. С JSON простыми 5. Джексон Не совсем уверен, что вам нужны все, но, по крайней мере, теперь вам не хватает httpcore


вы должны использовать проект BasicPhone Twilio SDK. Я пыталась дозвониться и теперь тоже могу позвонить. Этот проект имеет все методы и функции, которые вам нужно позвонить и отправить SMS. Прежде всего, вам нужен веб-сервис PHP, чтобы получить токен возможности и передать этот PHP-скрипт в ваше приложение.


вот как я решил свою потребность. открытый класс TwilioAsyncTask расширяет 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();