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
- As of the moment, I downloaded the binary 4.2.3.zip
- When you extracted the zip file, find the lib folder and copy all the jar files there
- Copy those jar files to your project’s lib folder, here’s how to do that:
- Go to your workspace directory, find your project folder and inside, find the libs folder, put the jar files we extracted earlier
- 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.
HOW TO POST TEXT DATA?
// url where the data will be posted 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" )); 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 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 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" )); 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 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" ?> 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.
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!
How to Send Data From Android to PHP Server? Android Post Request Help