2016-03-30 85 views
0

如何在Android中使用Twillio Api發送短信。 這是我的代碼。 我不知道的是如何設置http請求體。 當我使用CocoaRestClient(api測試工具)對其進行測試時,它運行良好。 請幫助我。如何在Android中使用Twilio Api發送短信

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:%[email protected]/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(); 
} 

}

+0

有人幫我嗎? :( –

+0

[此頁上的解決方案](http://stackoverflow.com/a/38871516/5486128)可能會幫助您 – TarikW

+0

看看這裏http://stackoverflow.com/questions/28109087/how-to-send -sms-using-twilio-in-my-android-application/41745246#41745246 – Sam

回答

0

梅根從Twilio這裏。

不推薦直接從移動應用程序與Twilio REST API交互。

從Android發送短信時,我會建議您有一個服務器組件using your language of choice。這使您可以保密您的API憑證。然後

您的移動應用程序將連接到您的服務器發出請求爲通過REST API與從參數發送短信,要和身體的消息:

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

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

請讓我知道這是否有幫助!

如果您可以另外提供一個示例錯誤消息,您可能會收到您的代碼,我可以仔細看看。

+0

謝謝你的回答。但是這對我不適用。 它給了我許多錯誤。對不起。 如果你認爲我使用了錯誤的庫,你能給我的jar文件的網址? –

+0

嗨威廉斯,如果你不關心安全風險,解決方法是修改twilio-java代碼以刪除對錯誤組件的依賴關係,然後重新生成。 jar文件。不幸的是,我沒有jar文件提供。 以前有關於Github上的這種不兼容性的討論: https://github.com/twilio/twilio-java/search?q=android&type=Issues –