Search code examples
javaphpandroidclient-serverhttpconnection

Sending POST data in Android


I'm experienced with PHP, JavaScript and a lot of other scripting languages, but I don't have a lot of experience with Java or Android.

I'm looking for a way to send POST data to a PHP script and display the result.


Solution

  • Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example

    Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.

        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());
                }
            }
        }
    

    References:

    Original Answer (May 2010)

    Note: This solution is outdated. It only works on Android devices up to 5.1. Android 6.0 and above do not include the Apache http client used in this answer.

    Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

    public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
    
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }