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!


51 responses to “How to Send Data From Android to PHP Server? Android Post Request Help”

  1. 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

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

  2. 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?

  3. 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?

  4. 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

    • Hey you could use it, its complete code here

      android code start here

      package com.example.xxx;

      import java.util.Calendar;

      import android.app.Activity;
      import android.app.DatePickerDialog;
      import android.app.Dialog;
      import android.content.Intent;
      import android.os.Bundle;
      import android.text.Editable;
      import android.text.TextWatcher;
      import android.util.EventLogTags.Description;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.DatePicker;
      import android.widget.EditText;
      import android.widget.TextView;
      import android.widget.Toast;
      import java.io.BufferedReader;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.util.ArrayList;
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.NameValuePair;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.message.BasicNameValuePair;
      import org.json.JSONException;
      import org.json.JSONObject;
      import android.annotation.SuppressLint;
      import android.annotation.TargetApi;
      import android.app.Activity;
      import android.content.Intent;
      import android.os.Build;
      import android.os.Bundle;
      import android.os.StrictMode;
      import android.util.Log;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.EditText;
      import android.widget.TextView;
      import android.widget.Toast;

      @SuppressLint(“NewApi”)
      public class xxx extends Activity{ //implements OnClickListener

      @SuppressLint(“NewApi”)
      StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();

      Button post;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.xxx);

      post =(Button)findViewById(R.id.postButton);
      post.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
      // TODO Auto-generated method stub

      String result = null;
      InputStream is = null;

      EditText editText=(EditText)findViewById(R.id.name_forkeyfound);
      String name=editText.getText().toString();

      EditText editText6=(EditText)findViewById(R.id.contect_keyfound);
      String contact_no=editText6.getText().toString();

      EditText editText3=(EditText)findViewById(R.id.Email_forkeyfound);
      String email=editText3.getText().toString();

      EditText editText8=(EditText)findViewById(R.id.membership_keyfound);
      String membership=editText8.getText().toString();

      EditText editText9=(EditText)findViewById(R.id.description_keyfound);
      String we_found=editText9.getText().toString();

      Log.d(“well2”, “msg”);

      ArrayList nameValuePairs = new ArrayList();

      nameValuePairs.add(new BasicNameValuePair(“name”,name));

      nameValuePairs.add(new BasicNameValuePair(“email”,email));

      nameValuePairs.add(new BasicNameValuePair(“contact_no”,contact_no));

      nameValuePairs.add(new BasicNameValuePair(“membership”,membership));

      nameValuePairs.add(new BasicNameValuePair(“we_found”,we_found));

      Log.d(“well2”, “msg”);
      StrictMode.setThreadPolicy(policy);

      Log.d(“well3”, “msg”);
      //http post
      try{
      HttpClient httpclient = new DefaultHttpClient();

      HttpPost httppost = new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/xxx.php”);

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      HttpResponse response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();
      is = entity.getContent();
      Log.d(“well4”, “msg”);

      Log.e(“log_tag”, “connection success “);
      Toast.makeText(getApplicationContext(), “Please Wait….”, Toast.LENGTH_SHORT).show();
      }

      catch(Exception e)
      {
      Log.e(“log_tag”, “Error in http connection “+e.toString());
      Toast.makeText(getApplicationContext(), “Connection fail”, Toast.LENGTH_SHORT).show();
      Log.d(“well5”, “msg”);

      }
      //convert response to string

      Log.d(“well5”, “msg”);
      try{
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,”iso-8859-1″),8);
      StringBuilder sb = new StringBuilder();
      Log.d(“well6”, “msg”);
      String line = null;
      while ((line = reader.readLine()) != null)
      {
      sb.append(line + “n”);
      Intent i = new Intent(getBaseContext(),keyfound.class);
      startActivity(i);
      }
      is.close();

      result=sb.toString();
      }
      catch(Exception e)
      {
      Log.e(“log_tag”, “Error converting result “+e.toString());
      Log.d(“well7”, “msg”);
      }

      try{

      JSONObject json_data = new JSONObject(result);

      CharSequence w= (CharSequence) json_data.get(“re”);
      Log.d(“well8”, “msg”);

      Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();

      }

      catch(JSONException e)
      {
      Log.e(“log_tag”, “Error parsing data “+e.toString());
      Log.d(“well8”, “msg”);
      Toast.makeText(getApplicationContext(), “JsonArray fail” +
      “l”, Toast.LENGTH_SHORT).show();
      Log.d(“well9”, “msg”);
      }

      }
      });

      }
      }

      xml file

  5. hi., thanks for your code.. but I have a problem I tried sending any file to the server and changed the php code a little into this
    php

    $data = $_POST[‘Quantity’];
    $filename = $_POST[‘FileName’];

    $file = $_FILES[‘file’];
    $fileContents = file_get_contents($file[“tmp_name”]);
    file_put_contents($filename, $fileContents);

    $file1= ‘logs.txt’;
    $current = file_get_contents($file1);
    $current .= ‘Data Inserted:’.PHP_EOL;
    $current .= ‘Image Name: ‘.$filename.PHP_EOL;
    $current .= ‘Image Quantity:’. $data . PHP_EOL;

    $current .= ‘Time Recieved’ . $today = date(“F j, Y, g:i a”);
    $current .= PHP_EOL . PHP_EOL;
    file_put_contents($file1, $current);

    //$fileContents = file_get_contents($file[“tmp_name”]);
    print_r($data.$fileContents);

    though it creates a file, but it has 0 bytes.. I don’t really know what to do..

    • Hello @ayamsakata:disqus, you have to make sure your PHP variables are the same with the one send by Android.

  6. this is brilliant! I had so much trobule trying to send my data. I have one more question, Im getting the right responses from server but I would also like to view send data somewhere. Im only sending strings. I guess I need to do this by php file, do you have any suggestions?

    • Sorry for the late reply @disqus_f6qeoT2J9P:disqus, but it case you or other people still need it, first yes, you need some server scripting like PHP and then you can process the data sent by Android there. Second, the code above can send files already, not just strings…

  7. Dear Sir,
    thanks for this tutorial it was very useful to understand how things work
    and most impotently the only solution without an error for the text data.

    although there are some codes in the file data that are deprecated.

    Thanks

  8. Hello,

    Getting error when I clicked on app
    as following : “Unfortunately, MyApp has stopped”

    I am getting following error in log file :
    E/Trace(685): error opening trace file: No such file or directory (2)

  9. Hi Sir,
    Thanks for this useful tutorial.
    I can implement this demo successfully.
    But I want to use this for my login form.
    User will enter username and password this info will send to php file on server and it return userid.
    I don’t understand how to call this postText() method on “login” button’s click event.
    Please, help me.

  10. maybe my question is stupid, I’m a beginner, but what is yourdomain.com ? what we have to write instead yourdomain.com ?

    • Hello @disqus_n7i9D5EGNE:disqus, yourdomain.com is your website. For example, in my case it’s codeofaninja.com

  11. I am trying to unicode with large size but always null here is my code:

    private class JSONTransmitter_savepesan extends
    AsyncTask {

    String url;

    private void Seturl(String txt) {
    url = txt;
    }

    @Override
    protected JSONObject doInBackground(JSONObject… data) {
    JSONObject json = data[0];
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(),
    100000);

    JSONObject jsonResponse = null;
    HttpPost post = new HttpPost(url);
    try {
    StringEntity se = new StringEntity(“json=” + json.toString(),”UTF-8″);
    post.addHeader(“content-type”,
    “application/x-www-form-urlencoded”);
    post.setEntity(se);

    HttpResponse response;
    response = client.execute(post);
    String resFromServer = org.apache.http.util.EntityUtils
    .toString(response.getEntity());

    jsonResponse = new JSONObject(resFromServer);

    Log.i(“Response from server”, jsonResponse.getString(“idpesan”));

    } catch (Exception e) {
    Log.i(“ga konek from server”, e.getMessage());
    e.printStackTrace();
    }

    return jsonResponse;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
    // TODO Auto-generated method stub
    try {

    if (result.getString(“idpesan”).length() > 0) {

    // idpesan = result.getString(“idpesan”).toString();

    //savekirim();

    Toast.makeText(getApplicationContext(),
    “pesan:”+result.getString(“idpesan”).toString(), Toast.LENGTH_SHORT)
    .show();

    } else {

    }

    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    super.onPostExecute(result);
    }

    }// end task

    i stuck at this moment. Can u help me thanks for your advice.

  12. Hi, Please i need help, the data wont show on my domain. I had hosted it and added the php file using filezilla, still i dont see any thing when i refresh the webpage.

  13. Hi Sir,
    I am am new to android, when am trying to execute the above code getting error in FileBody and MultipartEntity. Those classes are not there, even the eclipes is not giving suggestion on that. What will the mistake.

  14. Dear sir,
    thanks for this tutorial.
    I have a huge problem. I try this tutorial but I don’t arrive to post data on my server as only simple register. Please help me to this information on a server with “http post android”

    First name:
    Last name:
    email:
    telephone:
    city:
    country:
    address:
    — and button to submit —

  15. Yes we need to see any error messages from your logcat so that we can debug. Another way is to test your receiving URL first if it works, then test it with the Android script.

  16. Hi Mike Dalisay thank for your help, I need to send image on my online server when i send only text no probem but when i add image my code dont work and i try to use your one but i go a problem with your tutorial when i copy the lib on my Android studio 1.5 it give an error and i can not execute the code please help to resolve this issue because i need strongly this code to finish my work

  17. Hi,
    Nice tutorial, but i am facing some issue. Whenever I try to post something an empty response is recorded in the log cat, and when i check on the server a new blank line gets input.
    What am I doing wrong? Can you please help me out.

  18. Hi the app works fine withe the emulator but when I install it on my mobile, application crashes. Are there any solutions for that please

  19. heyy thanks for your quastion! Do you know how i can send a string from php to android? I have to convert it to JSON?

Leave a Reply

Your email address will not be published. Required fields are marked *