如何在Android中使用Twilio Api发送短信

时间:2016-03-30 19:07:58

标签: java android twilio

如何在Android中使用Twillio Api发送短信。 这是我的代码。 我不知道的是如何设置http请求体。 当我使用CocoaRestClient(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:%s@api.twilio.com/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();
}

}

1 个答案:

答案 0 :(得分:0)

来自Twilio的梅根在这里。

不建议直接从您的移动应用程序与Twilio REST API进行交互。

从Android发送短信时,我建议您使用服务器组件using your language of choice。这使您可以保密API凭证。

然后,您的移动应用程序将连接到您的服务器,以通过REST API发送SMS请求,其中包含消息的From,To和Body参数:

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

如果有帮助,请告诉我!

如果您可以提供一个示例错误消息,您可能会收到代码,我可以仔细查看。