检索字符串服务器响应code字符串、服务器、code

2023-09-07 10:16:15 作者:怪我懦弱i

我试图显示基于从服务器,但不知何故没有它每次的响应消息。当我通过提供其运行正常静态值运行从不同的项目java类单独在同一code和我能够得到的回应code。请参照code,帮我纠正错误。

MainActivity.java

 公共类MainActivity扩展活动实现OnClickListener,可运行{上下文语境;的EditText editTextNum,EDITTEXT,editUserName,editPassword;按钮btnsend;ProgressDialog PD;串gateway_name;线程t;微调spinner1;@覆盖公共无效的onCreate(捆绑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 =(微调)findViewById(R.id.SpinnerGateway);    btnsend =(按钮)findViewById(R.id.btnsend);    btnsend.setOnClickListener(本);}/ **当用户点击发送按钮调用* /公共无效的sendMessage(){    。字符串usrname = editUserName.getText()的toString();    。字符串usrPassword = editPassword.getText()的toString();    。弦数= editTextNum.getText()的toString();    字符串消息= editText.getText()的toString()。    gateway_name =将String.valueOf(spinner1.getSelectedItem());    字符串msgreciever =号;    字符串的TestMessage =消息;    尝试{        SmsSender.sendMessage(msgreciever,的TestMessage,usrname,                usrPassword,gateway_name);    }赶上(例外前){        Toast.makeText(MainActivity.this,短信发送失败,                Toast.LENGTH_SHORT).show();    }}@覆盖公共布尔onCreateOptionsMenu(菜单菜单){    。getMenuInflater()膨胀(R.menu.activity_main,菜单);    返回true;}@覆盖公共布尔onOptionsItemSelected(菜单项项){    //处理项目选择    开关(item.getItemId()){    案例R.id.menu_settings:        settingmenuClicked();        返回true;    案例R.id.menu_help:        showHelp();        返回true;    案例R.id.menu_inbox:        showInbox();        返回true;    默认:        返回super.onOptionsItemSelected(项目);    }}公共布尔isOnline(){    ConnectivityManager厘米=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);    NetInfo的的NetworkInfo = cm.getActiveNetworkInfo();    如果(NetInfo的= NULL&放大器;!&安培; netInfo.isConnectedOrConnecting()){        返回true;    }    返回false;}公共布尔的isValid(){    如果(editUserName.getText()。长度()== 10            &功放;&安培; editPassword.getText()。长度()!= 0            &功放;&安培; editTextNum.getText()。长度()== 10            &功放;&安培; editText.getText()。长度()!= 0){        返回true;    }    返回false;}公共无效的onClick(视图v){    // TODO自动生成方法存根    如果(V == btnsend){        如果(!isOnline()){            Toast.makeText(MainActivity.this,                    没有互联网Access..Cannot发送短信                    Toast.LENGTH_SHORT).show();        }否则如果(!的isValid()){            Toast.makeText(MainActivity.this,                    所有字段都是必需的。重试,                    Toast.LENGTH_SHORT).show();        }其他{            PD = ProgressDialog.show(MainActivity.this,免费短信                    发送SMS..Please等待.. !!,真正的);            T =新的Thread(本);            t.start();        }    }}公共无效settingmenuClicked(){    Toast.makeText(MainActivity.this设置菜单即将推出,            Toast.LENGTH_SHORT).show();}公共无效showHelp(){    Toast.makeText(MainActivity.this,帮助即将推出,            Toast.LENGTH_SHORT).show();}公共无效showInbox(){    //意向意图=新意图(这一点,Inbox.class);    // startActivity(意向);}公共无效的run(){    // TODO自动生成方法存根    发信息();    mHandler.sendEmptyMessage(0);}公共处理器mHandler =新的处理程序(Looper.getMainLooper()){    @覆盖    公共无效的handleMessage(消息MSG){        // TODO自动生成方法存根        super.handleMessage(MSG);        pd.dismiss();        字符串的响应= SmsSender.response code;        如果(响应==1){            Toast.makeText(MainActivity.this,消息发送成功,Toast.LENGTH_SHORT).show();        }否则如果(响应==-1){            Toast.makeText(MainActivity.this服务器错误,Toast.LENGTH_SHORT).show();        }否则如果(响应==-2){            Toast.makeText(MainActivity.this,无效的用户名,Toast.LENGTH_SHORT).show();        }否则如果(响应==-3){            Toast.makeText(MainActivity.this,无效消息文本,Toast.LENGTH_SHORT).show();        }否则如果(响应==-4){            Toast.makeText(MainActivity.this,登录失败,Toast.LENGTH_SHORT).show();        }否则如果(响应==-5){            Toast.makeText(MainActivity.this,IP被封锁,Toast.LENGTH_SHORT).show();        }其他{            Toast.makeText(MainActivity.this,未知错误,Toast.LENGTH_SHORT).show();        }        //Toast.makeText(MainActivity.this,消息向服务器发送            // Toast.LENGTH_SHORT).show();        editTextNum.setText();        editText.setText();        editTextNum.requestFocus();    }};} 

SmsSender.java

 公共类SmsSender {静态最后弦乐_url =htt​​p://ubaid.tk/sms/sms.aspx;静态最终字符串charset =UTF-8;公共静态字符串响应code =0;//建立查询字符串,将发送消息私有静态字符串buildRequestString(字符串targetPhoneNo,        消息字符串,字符串username,字符串password,字符串网关)抛出UnsupportedEncodingException {    的String [] = PARAMS新的String [5];    PARAMS [0] =用户名;    PARAMS [1] =密码;    PARAMS [2] =消息;    PARAMS [3] = targetPhoneNo;    PARAMS [4] =网关;    查询字符串=的String.format(            UID =%S&安培; PWD =%S&安培;味精=%S&安培;电话=%S&放大器;提供商=%S,            URLEn coder.en code(PARAMS [0],即charset)            URLEn coder.en code(PARAMS [1],字符集)            URLEn coder.en code(PARAMS [2],字符集)            URLEn coder.en code(PARAMS [3],字符集)            URLEn coder.en code(PARAMS [4],字符集));    返回查询;}公共静态无效的sendMessage(字符串reciever,字符串信息,用户名字符串,字符串密码,字符串网关)        抛出异常{    //要建立连接并执行POST请求    URLConnection的连接=新的URL(_url +?            + buildRequestString(reciever,信息,用户名,密码,网关))的openConnection();    connection.setRequestProperty(接收字符集,字符集);    //这个自动闪光的要求,我们可以用它来确定    //响应状态    InputStream的响应= connection.getInputStream();    BR的BufferedReader =新的BufferedReader(新的InputStreamReader(响应));    的System.out.println(br.readLine());    响应code = br.readLine();}公共静态无效的主要(字串[] args)抛出异常{    // 去做    //字符串testPhoneNo =9876543210;    //字符串的TestMessage =发送邮件从Java是不是太硬;    //的sendMessage(testPhoneNo,的TestMessage);} } 

解决方案

我觉得你的太多副本的受害者,从的的例子的。我怀疑你得到的回应(否则你会遇到一个例外)。然后,您只是throwing它带到一个的System.out.println()。然后,当你去设置响应code 的的readLine()返回null。

我试图测试它为我自己,但我不能使用API​​印度以外。

联想服务器助力专利检索平台建设

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

 }

解决方案

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.