Home >Java >javaTutorial >How to Send POST Data to a PHP Script from Android?

How to Send POST Data to a PHP Script from Android?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 03:29:33180browse

How to Send POST Data to a PHP Script from Android?

How to Send POST Data in Android

For developers proficient in PHP, JavaScript, and other scripting languages but new to Java and Android, this guide provides a solution for sending POST data to a PHP script and displaying the result.

Updated Approach (Android 6.0 )

This updated solution leverages AsyncTask, which is recommended for background tasks in Android.

public class CallAPI extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String urlString = params[0]; // URL to call
        String data = params[1]; // Data to post

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();

            urlConnection.connect();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Original Approach (Android 5.1 and Below)

For devices running Android 5.1 and below, Apache HttpClient can be used:

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    try {
        HttpResponse response = httpclient.execute(httppost);
    } catch (Exception e) {
        // Handle exceptions
    }
}

The above is the detailed content of How to Send POST Data to a PHP Script from Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn