2015-01-23 28 views
8

Trong ứng dụng Android của tôi, tôi đã tạo ra một nút, khi tôi đã nhấn vào nút tôi muốn gửi tin nhắn. Do đó tôi đã tạo ra một lớp java và viết mã twilio.Làm thế nào để gửi tin nhắn SMS bằng Twilio trong ứng dụng Android của tôi?

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

khi tôi đang sử dụng đoạn mã trên nó hiển thị một số lỗi như java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager

Tôi đã thêm chỉ một file jar trong thư mục lib như " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".

xin vui lòng cho tôi biết những gì tôi có thể làm gì?

Trả lời

7

Tôi đã sử dụng phương pháp để HttpPost send sms ở chỗ tôi đã trôi qua url của tôi với xác thực cơ sở ở đây là mã của tôi

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

        } 
       } 

Nó đang làm việc tốt.

+0

Tôi đã sử dụng mã của bạn để gửi tin nhắn SMS về số lượng của riêng tôi nhưng phản ứng luôn luôn là như " +15005550006 Sent từ tài khoản thử nghiệm Twilio của bạn - Chào mừng bạn đến Twilio xếp hàng đợi outbound-api 2010-04-01 USD "Nhưng tôi đã không nhận được SMS. Tại sao điều này xảy ra? Tôi đang sử dụng thông tin đăng nhập thử nghiệm. – Hits

+0

trạng thái có được xếp hàng đợi, vì vậy nó sẽ đến sau một thời gian, khi tôi đang thử nghiệm ứng dụng của mình tại thời điểm đó, tôi cũng nhận được phản hồi tương tự. – Hanuman

+0

có ký tự không hợp lệ tại "https://api.twilio.com/2010-04-01/Accounts/{my-_ACCOUNT_SID}/SMS/Messages"); dòng? – Sam

0

Twilio Java SDK có phụ thuộc bên thứ ba mà không có chúng, nó sẽ không hoạt động. Sự phụ thuộc là: 1. httpcore 2. HttpClient 3. Commons lang 4. Json đơn giản 5. Jackson Không khá chắc chắn nếu bạn cần tất cả, nhưng ít nhất bây giờ bạn đang thiếu httpcore

+0

Nếu tôi đã thêm những "httpcore hoặc httpclient jar" file sau đó nó được hiển thị lỗi là "Nhiều file dex xác định Lorg/apache/http/ConnectionClosedException;" có nghĩa là cùng một lớp hoặc cùng một gói là avialble trong tập tin jar twilio-sdk-java. Vì vậy, nó đang hiển thị các lớp trùng lặp có sẵn – Hanuman

+0

jar twilio-sdk-java không có lớp này, lớp mà bạn đã đề cập chỉ có sẵn trong httpcore. jar, vì vậy có lẽ bạn có nhiều hơn thì một phiên bản của httpcore có sẵn? – Babl

+0

Tôi đã thêm các tệp jar như "twilio-java-sdk-3.3.10.jar, httpcore.jar, httpclient-4.3.jar" và lớp "org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager" hiện tại trong httpclient-4.3.jar nhưng nó hiển thị cùng lỗi mà Log-cat đang hiển thị như thế này – Hanuman

0

Bạn nên sử dụng dự án BasicPhone của Twilio SDK. Tôi đã thử điều này để gọi và bây giờ tôi cũng có thể gọi. Dự án này có tất cả các phương pháp và chức năng mà bạn cần gọi và gửi SMS. Trước hết, bạn cần một dịch vụ web PHP để nhận mã thông báo khả năng và truyền tập lệnh PHP đó vào ứng dụng của bạn.

4

Giải pháp này với 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 cho build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'

+0

ResponseBody bên trong Callback mới () cho lỗi – Sam

+0

Url API không còn muốn phần/SMS của đường dẫn. Bạn có thể cắt phần đó ra, như được thấy ở đây: https://www.twilio.com/console/dev-tools/api-explorer/sms/messages/create –

3

Phương pháp của tôi, sử dụng OkHttp:

1. Điều kiện tiên quyết

Gradle:

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

Manifest:

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

Giấy phép hoạt động:

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

2. Mã

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

} 

tôi đã sử dụng Allu tuyết e cho ủy quyền rộng rãi trong tiêu đề

0

Đây là cách tôi giải quyết được nhu cầu của mình. public class TwilioAsyncTask kéo dài 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(); 
Các vấn đề liên quan