Home >Backend Development >PHP Tutorial >How to Send POST Data in Android: AsyncTask vs. Modern Methods?

How to Send POST Data in Android: AsyncTask vs. Modern Methods?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 13:19:11742browse

How to Send POST Data in Android: AsyncTask vs. Modern Methods?

How to Send POST Data in Android

When developing for Android, it's essential to know how to send POST data to remote servers. This article provides a comprehensive guide on how to achieve this using both the deprecated AsyncTask and a more modern approach.

Deprecated AsyncTask Method

The following code snippet demonstrates how to send POST data using the AsyncTask class:

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

    public CallAPI() {
        //set context variables if required
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

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

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            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());
        }
    }
}

Updated Method for Android 6.0

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

The above is the detailed content of How to Send POST Data in Android: AsyncTask vs. Modern Methods?. 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