java - 通过第三方网关在 Android 上发送短信

标签 java android sms sms-gateway

请我想知道下面的代码有什么问题以及为什么它不发送短信,当我调试时没有发现错误。请问我可以获得帮助吗?

public class LaunchSMS extends Activity implements OnClickListener {

    private TextView phone;
    private TextView phone2;
    private EditText TFmsg;
    private TextView TVfrom;
    Button btnsend;
    static final String username = "xxxxxxx";
    static final String password = "xxxxxxx";
    static String url = "http://www.esmsafrica.com/components/com_spc/smsapi.php";

    static final String charset = "UTF-8";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display);

        TFmsg = (EditText) findViewById(R.id.TFmsg);
        phone = (TextView) findViewById(R.id.phone);
        btnsend = (Button) findViewById(R.id.btnsend);
        Button mBtnContacts = (Button) findViewById(R.id.mBtnContacts);
        Button btnLogout = (Button) findViewById(R.id.btnlogout);

        mBtnContacts.setOnClickListener(this);
        btnsend.setOnClickListener(this);
        btnLogout.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Uri uri = data.getData();

            if (uri != null) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, new String[]{
                                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.TYPE},
                            null, null, null);

                    if (c != null && c.moveToFirst()) {
                        String number = c.getString(0);
                        showSelectedNumber(number);
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            }
        }
    }

    public void showSelectedNumber(String number) {
        phone.setText(number);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mBtnContacts) {
            // user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            // BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            startActivityForResult(intent, 1);
        }

        if (v.getId() == R.id.btnsend) {

            String reciever = phone.getText().toString();
            String message = TFmsg.getText().toString();
            if (reciever.length() > 0 && message.length() > 0)
                try {
                    sendSMS(reciever, message);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            else
                Toast.makeText(getBaseContext(),
                        "Please enter both reciever number and message.",
                        Toast.LENGTH_SHORT).show();
        }

        if (v.getId() == R.id.btnlogout) {
            logoutUser();
        }
    }

    private void logoutUser() {
        Intent intent = new Intent(LaunchSMS.this, Sendsms.class);
        startActivity(intent);
        finish();
    }

    public static void sendSMS(String reciever, String message) throws Exception {
            System.out.println("Welcome to eSMS");
            //To establish the connection and perform the post request
            URLConnection connection = new URL(url + "?" + buildRequestString(reciever,message)).openConnection();
            connection.setRequestProperty("Accept-Charset", charset);

            //This automatically fires the request and we can use it to determine the response status
            InputStream response = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(response));
            //System.out.println(br);

            System.out.println(br.readLine());
        }

    private static String buildRequestString(String reciever, String message) throws UnsupportedEncodingException {
        String [] params = new String [5];
        params[0] = username;
        params[1] = password;
        params[2] = message;
        params[3] = reciever;
        params[4] = "esmsafrica";

        String query = String.format("uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
                URLEncoder.encode(params[0],charset),
                URLEncoder.encode(params[1],charset),
                URLEncoder.encode(params[2],charset),
                URLEncoder.encode(params[3],charset),
                URLEncoder.encode(params[4],charset)
        );
        return query;
    }

    public static void main(String [] args) throws Exception {
        System.out.println("enter Mobile No:");
        Scanner scanIn = new Scanner(System.in);

        String testPhoneNo = scanIn.nextLine();
        scanIn.close();
        String testMessage = "Sending Messages";
        sendSMS(testPhoneNo, testMessage);
    }
}

最佳答案

我已经实现了从 MSG91 发送短信消息服务。

public static void sendSMS(String reciever, String message) {
  URLConnection myURLConnection=null;
  URL myURL=null;
  BufferedReader reader=null;
  try
     {
     //prepare connection
     myURL = new URL(buildRequestString(reciever, message));
     myURLConnection = myURL.openConnection();
     myURLConnection.connect();
     reader= new BufferedReader(new     
     InputStreamReader(myURLConnection.getInputStream()));

     //reading response 
     String response;
     while ((response = reader.readLine()) != null) 
     //print response 
     Log.d("RESPONSE", ""+response);
     //finally close connection
     reader.close();
     } catch (IOException e) { 
        e.printStackTrace();
     }
 }

 private static String buildRequestString(String reciever, String message){
     //encoding message 
     String encoded_message=URLEncoder.encode(message);

     //Send SMS API
     String mainUrl="http://api.msg91.com/sendhttp.php?";

     //Prepare parameter string 
     StringBuilder sbPostData= new StringBuilder(mainUrl);
     sbPostData.append("authkey="+authkey); 
     sbPostData.append("&mobiles="+reciever);
     sbPostData.append("&message="+encoded_message);
     sbPostData.append("&route="+"4");
     sbPostData.append("&sender="+"CustomSenderID");
     return sbPostData.toString();
 }

关于java - 通过第三方网关在 Android 上发送短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32116408/

相关文章:

python noob 在发送谷歌语音文本时遇到问题

java - 嵌套 Maven 多模块相对于简单依赖的优势

java - 单击 selenium java 上的链接时出现问题

java - 如果用户打开 youtube,如何终止 Android 进程

java - Android点击按钮自动发送短信

android - 捕捉短信发送和传递事件

java - 如何在 TestRunner 中从 Hooks 类调用 @Before 方法?

java - 如何使用规范在mysql查询中使用多个 "OR"条件创建两个 "AND"条件

android - FaSTLane Android Build 在颤振问题

android - “R 无法解析为变量”- gen 文件夹为空