Home >Java >javaTutorial >How to Send POST Data in Android Using HttpURLConnection?

How to Send POST Data in Android Using HttpURLConnection?

DDD
DDDOriginal
2024-12-25 10:14:12746browse

How to Send POST Data in Android Using HttpURLConnection?

Sending POST Data in Android

POST requests are used to send data to a server in order to create or update a resource, typically in the form of a web form. In this case, the task is to send POST data to a PHP script on a server and display the results.

Solution (Updated for Android 6.0 ):

The recommended approach is to use the HttpURLConnection class. Here's a Java snippet demonstrating how to send POST data:

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

    @Override
    protected String doInBackground(String... params) {
        String urlString = params[0];
        String data = params[1];
        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());
        }

        return null;
    }
}

Original Solution (Outdated for Android 6.0 ):

Prior to Android 6.0, the Apache HttpClient library could be used for HTTP Post requests:

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

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    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
    }
}

References:

  • https://developer.android.com/reference/java/net/HttpURLConnection.html
  • How to add parameters to HttpURLConnection using POST using NameValuePair

The above is the detailed content of How to Send POST Data in Android Using HttpURLConnection?. 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