retrieve server response code in string

2019-06-09 03:01发布

I am trying to display the message based on the response from the server but somehow its failing everytime. When i am running the same code from java class seperately from different project by providing static values it is running properly and i am able to get the response code. Please refer the code and help me rectify the error.

MainActivity.java

public class MainActivity extends Activity implements OnClickListener, 
Runnable {
Context context;
EditText editTextNum, editText, editUserName, editPassword;
Button btnsend;
ProgressDialog pd;
String gateway_name;
Thread t;
Spinner spinner1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    editUserName = (EditText) findViewById(R.id.edit_userName);
    editPassword = (EditText) findViewById(R.id.edit_password);
    editTextNum = (EditText) findViewById(R.id.edit_number);
    editText = (EditText) findViewById(R.id.edit_message);
    spinner1 = (Spinner) findViewById(R.id.SpinnerGateway);
    btnsend = (Button) findViewById(R.id.btnsend);
    btnsend.setOnClickListener(this);
}

/** Called when the user clicks the Send button */
public void sendMessage() {
    String usrname = editUserName.getText().toString();
    String usrPassword = editPassword.getText().toString();
    String number = editTextNum.getText().toString();
    String message = editText.getText().toString();
    gateway_name = String.valueOf(spinner1.getSelectedItem());
    String msgreciever = number;
    String testMessage = message;
    try {
        SmsSender.sendMessage(msgreciever, testMessage, usrname,
                usrPassword, gateway_name);
    } catch (Exception ex) {
        Toast.makeText(MainActivity.this, "SMS Sending Failed.",
                Toast.LENGTH_SHORT).show();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menu_settings:
        settingmenuClicked();
        return true;
    case R.id.menu_help:
        showHelp();
        return true;
    case R.id.menu_inbox:
        showInbox();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public boolean isValid() {
    if (editUserName.getText().length() == 10
            && editPassword.getText().length() != 0
            && editTextNum.getText().length() == 10
            && editText.getText().length() != 0) {
        return true;
    }
    return false;
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    if (v == btnsend) {
        if (!isOnline()) {
            Toast.makeText(MainActivity.this,
                    "No Internet Access..Cannot Send SMS",
                    Toast.LENGTH_SHORT).show();
        } else if (!isValid()) {
            Toast.makeText(MainActivity.this,
                    "All fields are required. Try Again.",
                    Toast.LENGTH_SHORT).show();
        } else {
            pd = ProgressDialog.show(MainActivity.this, "Free Sms",
                    "Sending SMS..Please Wait..!!", true);
            t = new Thread(this);
            t.start();
        }

    }
}

public void settingmenuClicked() {
    Toast.makeText(MainActivity.this, "Setting Menu Coming Soon",
            Toast.LENGTH_SHORT).show();
}

public void showHelp() {
    Toast.makeText(MainActivity.this, "Help Coming Soon",
            Toast.LENGTH_SHORT).show();
}

public void showInbox() {
    //Intent intent = new Intent(this, Inbox.class);
    //startActivity(intent);
}

public void run() {
    // TODO Auto-generated method stub
    sendMessage();
    mHandler.sendEmptyMessage(0);
}

public Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        pd.dismiss();
        String response = SmsSender.responsecode;
        if(response == "1"){
            Toast.makeText(MainActivity.this, "Message Sent Successfully",Toast.LENGTH_SHORT).show();
        } else if(response == "-1"){
            Toast.makeText(MainActivity.this, "Server Error",Toast.LENGTH_SHORT).show();
        } else if(response == "-2"){
            Toast.makeText(MainActivity.this, "Invalid Username",Toast.LENGTH_SHORT).show();
        } else if(response == "-3"){
            Toast.makeText(MainActivity.this, "Invalid Message Text",Toast.LENGTH_SHORT).show();
        } else if(response == "-4"){
            Toast.makeText(MainActivity.this, "Login Failed",Toast.LENGTH_SHORT).show();
        } else if(response == "-5"){
            Toast.makeText(MainActivity.this, "IP is blocked",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Unknown Error",Toast.LENGTH_SHORT).show();
        }
        //Toast.makeText(MainActivity.this, "Message Sent To Server",
            //  Toast.LENGTH_SHORT).show();
        editTextNum.setText("");
        editText.setText("");
        editTextNum.requestFocus();
    }
};
}

SmsSender.java

public class SmsSender {

static final String _url = "http://ubaid.tk/sms/sms.aspx";
static final String charset = "UTF-8";
public static String responsecode = "0";

// to build the query string that will send the message
private static String buildRequestString(String targetPhoneNo,
        String message, String userName, String Password, String Gateway) throws UnsupportedEncodingException {
    String[] params = new String[5];
    params[0] = userName;
    params[1] = Password;
    params[2] = message;
    params[3] = targetPhoneNo;
    params[4] = Gateway;

    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 sendMessage(String reciever, String message, String userName, String password, String Gateway)
        throws Exception {
    // To establish the connection and perform the post request
    URLConnection connection = new URL(_url + "?"
            + buildRequestString(reciever, message, userName, password, Gateway)).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.readLine());
    responsecode = br.readLine();

}

public static void main(String[] args) throws Exception {
    // To DO
    //String testPhoneNo = "9876543210";
    //String testMessage = "Sending Messages From java is not too hard";
    //sendMessage(testPhoneNo, testMessage);
}

 }

1条回答
干净又极端
2楼-- · 2019-06-09 03:26

I think you are a victim of too much copy and paste from the example. I suspect you are getting a response (otherwise you would encounter an exception). You are then are just throwing it away to a System.out.println(). Then when you go to set responsecode readLine() returns null.

I tried to test it for myself, but I cannot use the API outside of India.

查看更多
登录 后发表回答