如何在我的 android 应用程序中使用 Twilio 发送短信?

How to send SMS using Twilio in my android application?

在我的 android 应用程序中,我创建了一个按钮,当我按下要发送的按钮时 message.So 为此,我创建了一个 java class 和编写的 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

我在 lib 文件夹中只添加了一个 jar 文件 " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".

请告诉我我能做什么?

Twilio Java SDK 具有第三方依赖项,没有它们将无法工作。依赖项是: 1.http核心 2.http客户端 3. 通用语言 4. Json简单 5.杰克逊 不太确定你是否需要它们,但至少现在你缺少 httpcore

您应该使用Twilio SDK 的BasicPhone 项目。我试过用这个打电话,现在我也可以打电话了。该项目具有您需要调用和发送 SMS 的所有方法和功能。首先,您需要一个 PHP 网络服务来获取功能令牌并将该 PHP 脚本传递到您的应用程序中。

我已将 HttpPost 方法用于 send 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) {

                    }
                }

运行良好。

这个带有 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
    );
}

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"/>

activity 中的权限:

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代码在header中生成授权

这就是我解决需求的方法。 public class 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();