How to Send Data From Android to PHP Server? Android Post Request Help

Hi guys! Today we are going to code on how to send data from Android to PHP server. This is an example app that can post a file and text data to a web server with PHP file as a receiver. Having the ability to (do HTTP Post Request) post data from android app to remote server is required for most apps. Here are some example use of this functionality:

1. You want to get statistics on how your app is being used (you have to tell your user and they must agree of course!)
2. Your app has an upload file feature.
3. A user should register on your database before using more features of your app.

DOWNLOAD SOURCE CODE

Download HttpComponents Library

In this example, we are using a small library for posting a file, it is called the HttpComponents from the Apache Software Foundation. Please note that you won’t need this library if you’re just posting text data. The download can be found here: HttpComponents

  1. As of the moment, I downloaded the binary 4.2.3.zip
  2. When you extracted the zip file, find the lib folder and copy all the jar files there
  3. Copy those jar files to your project’s lib folder, here’s how to do that:
  4. Go to your workspace directory, find your project folder and inside, find the libs folder, put the jar files we extracted earlier
  5. Go back to eclipse and refresh your project files in the project explorer, now you can see the jar files inside your lib directory. See the screenshot below to visualize the goal of these 5 steps above.

Library Import - How to Send Data From Android to PHP Server?

How To Post Text Data?

// url where the data will be posted
String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);

// HttpClient
HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);

// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("firstname", "Mike"));
nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
nameValuePairs.add(new BasicNameValuePair("email", "mike@testmail.com"));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {
    
    String responseStr = EntityUtils.toString(resEntity).trim();
    Log.v(TAG, "Response: " +  responseStr);
    
    // you can add an if statement here and do other actions based on the response
}

How To Post A File?

You can use this code to post other file types such as an image.

// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
Log.v(TAG, "textFile: " + textFile);

// the URL where the file will be posted
String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);

// new HttpClient
HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);

File file = new File(textFile);
FileBody fileBody = new FileBody(file);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);

// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {
    
    String responseStr = EntityUtils.toString(resEntity).trim();
    Log.v(TAG, "Response: " +  responseStr);
    
    // you can add an if statement here and do other actions based on the response
}

Complete Android Code on How to Send Data From Android to PHP Server

This is our MainActivity.java code. In this code, we are:

  • Using AsyncTask to prevent the network on main thread error.
  • To test posting the text data, you must change the actionChoice variable value to 1.
  • Else if you are to test posting a sample file, you must change the actionChoice to 2. Also, don’t forget to put a sample.txt file in your SD card root directory.
package com.example.androidpostdatatophpserver;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.app.Activity;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity.java";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // we are going to use asynctask to prevent network on main thread exception
        new PostDataAsyncTask().execute();
        
    }

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

        protected void onPreExecute() {
            super.onPreExecute();
            // do stuff before posting data
        }

        @Override
        protected String doInBackground(String... strings) {
            try {

                // 1 = post text data, 2 = post file
                int actionChoice = 2;
                
                // post a text data
                if(actionChoice==1){
                    postText();
                }
                
                // post a file
                else{
                    postFile();
                }
                
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String lenghtOfFile) {
            // do stuff after posting data
        }
    }
    
    // this will post our text data
    private void postText(){
        try{
            // url where the data will be posted
            String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);
            
            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            
            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);
    
            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("firstname", "Mike"));
            nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
            nameValuePairs.add(new BasicNameValuePair("email", "mike@testmail.com"));
            
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            
            if (resEntity != null) {
                
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);
                
                // you can add an if statement here and do other actions based on the response
            }
            
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // will post our text file
    private void postFile(){
        try{
            
            // the file to be posted
            String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
            Log.v(TAG, "textFile: " + textFile);
            
            // the URL where the file will be posted
            String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);
            
            // new HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            
            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);
            
            File file = new File(textFile);
            FileBody fileBody = new FileBody(file);
    
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file", fileBody);
            httpPost.setEntity(reqEntity);
            
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
    
            if (resEntity != null) {
                
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);
                
                // you can add an if statement here and do other actions based on the response
            }
            
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The code above should give you a lot of clue on how to send data from Android to PHP server. But we have few more steps to do, continue to read below.

PHP file that will receive the posted data

This is the post_date_receiver.php code. You must upload it in your server and specify the URL to our MainActivity.java

<?php
// if text data was posted
if($_POST){
    print_r($_POST);
}

// if a file was posted
else if($_FILES){
    $file = $_FILES['file'];
    $fileContents = file_get_contents($file["tmp_name"]);
    print_r($fileContents);
}
?>

AndroidManifest.xml Code

Well, we are just having an INTERNET permission here.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidpostdatatophpserver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidpostdatatophpserver.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output Screenshots

Response is what post_date_receiver.php outputs when it receives the posted data.

android http example - posting text data output

Posting Text Data. The response array have our key-value pairs.

Posting Text File. The response is the content of my sample.txt file.

Posting Text File. The response is the content of my sample.txt file.

What do you think fo this code I came up with? If you have a better solution about how to send data from Android to PHP server, please let us know in the comments section below! We will add your solution or update this post if it deserves to, thanks!

The Code of a Ninja Resources

  • Curious Android Developer

    Do you have any suggestion when we want to send BOTH string and file in one go? Suppose we want to create a feature which user can post a picture with some captions. How do we proceed with that?

    Thanks

    • ninjazhai

      Hey @Curious, how about putting those two methods in a single method and execute one after the other?

  • Don MacLeod

    I’m trying to post data to a website from Android. The website just shows empty. How does the website refresh when it gets data? is the command $_POST always looking for data or does it only see the second it is sent?

  • Rohan D

    The php server i’m trying to upload my file to requires authentication. How can i send the username and password before attempting the upload?

    • ninjazhai

      Hi @Rohan D, thanks for your query, I’ll have to make a new post for this one!

  • prachi

    Dear Sir,
    I need help in sending data to server with android code.I have an api example
    http://getepass.com/api.php?action=login&&email=aaa@gmail.com&&password=root
    I want to send email and password to server from mobile text and receive few parameter image ,name,compid etc and then show in app.
    I am using a lib for this but I want to code it myself If possible please send me the example to post and read the json from server in android.
    Thanks!
    Prachi Gupta

  • ninjazhai

    Hi @disqus_JenUx8eReG:disqus, thanks for sharing your code!