当前位置: 首页 > 知识库问答 >
问题:

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

穆季萌
2023-03-14

如何在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个答案

席烨
2023-03-14

我是Twilio的梅根。

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

当从Android发送SMS时,我建议您使用您选择的语言来使用服务器组件。这允许您对API凭据保密。

// 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()); 
 } 
}
 类似资料:
  • 问题内容: 从Java应用程序发送和接收短信的可能方法是什么? 问题答案: 如果您想要的只是简单的通知,许多运营商都支持通过电子邮件发送短信;通过电子邮件查看短信

  • 问题内容: 首先,我真的很惊讶这不是重复的,因为在Objective-C中有大量的堆栈溢出问题可以解决这个问题,但是我还没有看到使用Swift的好答案。 我正在寻找的是Swift中的代码段,该代码段将任意字符串作为文本消息的正文发送到给定的电话号码。从本质上讲,我希望像这样从苹果的官方文档,但是在斯威夫特,而不是Objective- C的。 我认为这并不是太困难,因为可以在Android中只需几行

  • 查看:app/views/home/index.html.erb 路线:

  • 问题内容: 我想创建一个带有自定义线程ID的SMS,例如“ 10001”。我怎样才能做到这一点 ?原因是因为我需要实现删除SMS功能,并且删除特定SMS线程的唯一方法是通过线程ID或电话号码,并且此时无法准确获取电话号码,因此需要定义自定义线程ID在我发送短信时。 到目前为止,我只能获得正常的SMS工作代码,如下所示: 在此先感谢您的帮助! 问题答案: 的类是该寄存器本身上的 反对接收者的地址和消

  • 我想知道我是否可以用非默认短信应用程序发送短信。

  • 我希望我的Java应用程序在不使用任何额外硬件设备的情况下发送和接收短信,而且它必须是免费的。 我进行了搜索,但我只找到了标题,我找到了一些类似SMSLib的东西,但另一方面,我没有找到学习这些的教程或书籍。 我还发现了SMSLib代码,但不明白: 发送消息/短信代码 阅读信息/短信代码