Call a PHP function from Android?

I want to call a specific php function on the server from an Android application, and also send some parameters. So far, I have ensured that I can open the php file using HttpClient and do the Json data transfer and show it in my application. So now I want to be able to call a specific function and send it a parameter, how can I do this? Thank.

+3
source share
3 answers

Here is a piece of code that I wrote to register a new username using JSON:

    public static boolean register(Context myContext, String name, String pwd) {

            byte[] data;
            HttpPost httppost;
            StringBuffer buffer;
            HttpResponse response;
            HttpClient httpclient;
            InputStream inputStream;
            List<NameValuePair> nameValuePairs;

            try {
                    httpclient = new DefaultHttpClient();
                    httppost = new HttpPost(
                                    "http://X.X.X.X/register.php");
                    // Add your data
                    nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
                    nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    response = httpclient.execute(httppost);
                    inputStream = response.getEntity().getContent();

                    data = new byte[256];

                    buffer = new StringBuffer();
                    int len = 0;
                    while (-1 != (len = inputStream.read(data))) {
                            buffer.append(new String(data, 0, len));
                    }

                    inputStream.close();
            }

            catch (Exception e) {
                    Toast.makeText(myContext, "error" + e.toString(), Toast.LENGTH_LONG)
                                    .show();
                    return false;
            }


            if (buffer.charAt(0) == 'Y') {

                    return true;
            } else {

                    return false;
            }

    }

If you notice:

            nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
                    nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

in this part you can send parameters.

register.php. , "N"; "Y".

POST, :

 $user = $_POST['User'];

:)

!

+4

php - -, , .

+1

All Articles