简体   繁体   English

如何在Android中将php echo读入字符串?

[英]How to read the php echo into string in Android?

How to read the php echo into string in Android? 如何在Android中将php echo读入字符串?

I want to get the echo response with success or failure. 我想获得成功或失败的回声响应。

If user login into the page, if the user name doesn't match in database it should not allow the user to login and show some failure message. 如果用户登录页面,如果用户名在数据库中不匹配,则不应允许用户登录并显示一些失败消息。

MainActivity class MainActivity类

public class MainActivity extends Activity implements OnClickListener {

    EditText name,number;
    Button login; 
    SetContact contact;

    Boolean isInternetPresent = false;
    ConnectionDetector cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact);

        cd = new ConnectionDetector(getApplicationContext());


        name = (EditText) findViewById(R.id.etname);
        number = (EditText) findViewById(R.id.etnumber);

        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(this);
    }

    public static String POST(String url, SetContact contact){
        InputStream inputStream = null;
        String result = "";
        try {


            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);

            String json = "";

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", contact.getName());
            jsonObject.accumulate("number", contact.getNumber());



            json = jsonObject.toString();

            StringEntity se = new StringEntity(json);

            httpPost.setEntity(se);

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);

            inputStream = httpResponse.getEntity().getContent();

            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    public void onClick(View view) {

        String username = name.getText().toString();
        String password = number.getText().toString();
       /* if(username.equals("name") && password.equals("number")){


                Toast.makeText(getBaseContext(), "Username and password incorrect", Toast.LENGTH_LONG).show();
            } */     

    /*else {

            Toast.makeText(getBaseContext(), "Username does not exist. Please register.", Toast.LENGTH_LONG).show();
        }           */




        switch(view.getId()){
            case R.id.login:
                if(!validate()) {
                    Toast.makeText(getBaseContext(), "Please Enter Valid data!", Toast.LENGTH_LONG).show();
                } else {

                new HttpAsyncTask().execute("myurl?name="+username+"&number="+password);
                }
            break;
        }

    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            contact = new SetContact();
            contact.setName(name.getText().toString());
            contact.setNumber(number.getText().toString());


            return POST(urls[0],contact);
        }


        protected void onPostExecute(String result) {

            isInternetPresent = cd.isConnectingToInternet();

            if (isInternetPresent) {
                Toast.makeText(getBaseContext(), "Thanks for the Mail, We will Reply you soon", Toast.LENGTH_LONG).show();
                name.setText("");
                number.setText("");

                Intent in = new Intent(getApplicationContext(), Updates.class);
                startActivity(in);
            } else {

                showAlertDialog(MainActivity.this, "No Internet Connection",    "Please Connect Internet.", false);
            }                   
       }
    }


    private boolean validate(){




            if(name.length() > 25){
            Toast.makeText(getApplicationContext(), "pls enter less the 25 characher in user name", Toast.LENGTH_SHORT).show();


            return true;
        }

        else if(name.length() == 0 || number.length() == 0 ){
            Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
            return false;
        }

        else if(number.length() < 6 || number.length() > 13){

            number.setError("Not Valid Phone Number");
            return false;

        }
            return true;



    }
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    @SuppressWarnings("deprecation")
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();


        alertDialog.setTitle(title);

        alertDialog.setMessage(message);

        alertDialog.setIcon((status) ? R.drawable.fail : R.drawable.fail);

        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        alertDialog.show();
    }

}

Try this 尝试这个

HttpResponse response = client.execute(httpPost);

String responseBody = EntityUtils.toString(response.getEntity());

hint: Am using Print in php instead of echo 提示:我在php中使用Print而不是echo

Your question is very general, so my answer will be, too. 您的问题很笼统,我的答案也将是。 You can generate output in PHP eg via echo like "login failed" and evaluate it on the Android side. 您可以生成输出PHP例如,通过echo像“登录失败”,并评估其对Android一面。 Even better, you can use HTTP status codes to imply success or failure (like Unauthorized / 401) after login ( PHP side / Android side ). 更好的是,您可以在登录后( PHP端 / Android端 )使用HTTP状态代码来暗示成功或失败(例如Unauthorized / 401)。

Since you have no code, that actually does the login via a GET request, you should read on how to do this . 由于您没有代码,因此实际上是通过GET请求进行登录的,因此您应该阅读如何执行此操作

You should use JSON and not strings. 您应该使用JSON而不是字符串。

I use JsonSimple library to parse it to object. 我使用JsonSimple库将其解析为对象。

Here is my code to have an example: 这是我的示例代码:

HashMap<String, String> urlParams = new HashMap<String, String>();
    urlParams.put("KEY", Value);
    String result = "-1";
    try {
        result = rest.POST(host, "Response.php", this.header,
                urlParams, 3000);
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject json = new JSONObject();
    try {
        json = (JSONObject) new JSONParser().parse(result);
        return json.get("value_you_want").toString();
    } catch (ParseException e) {
        return ("Error parsing " + e.getMessage());

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM