REST API provides external interface to call some important functions of any Web based software. It’s very easy to write and test applications with REST APIs. Let’s say that we are building an application that we want to automatically upload an image file and submit a form data. In previous post we did the same thing from PHP. Now we’ll do it from Android application. Android applications frequently connect to the internet for data downloading or uploading to the server. REST APIs provide lightweight solution for this requirement. We suppose sample REST APIs and then write the code to call these REST APIs from Android App. We will use on the POST method for sending data to the server.


The first for any REST API is the URLs. We assume our base URL to be: 

Authentication information is also required for calling secure web services. We suppose following:

api_key: admin
api_secret: secret

We also need the information about REST API functions that we need to call. We assume following two REST functions.

Method: Contact_Create

Input Parameters:
* first_name
* last_name
* email

Returns json encoded string containing contact_id if successful.

Calling REST API – The Android Way

Following function createContact() calls the REST API. It will also authenticate and prepare the request and carry the request to REST Web Service. It has three arguments. First argument is the first_name, second argument is last_name and third is email address of the contact.

public static String createContact(String firstName, String lastName, String email){
	  HttpURLConnection conn = null;
	  DataOutputStream dos = null;
	  DataInputStream inStream = null;
	  String response = null;
	  SharedPreferences prefs = Globals.get().getPrefs();
	  String api_key = prefs.getString(Globals.PREF_API_KEY, "admin");
	  String api_secret = prefs.getString(Globals.PREF_API_SECRET, "secret");
	  String api_url = prefs.getString(Globals.PREF_API_URL, "");
	  String urlString = api_url + "Contact_Create?username=" + api_key + "&password=" + api_secret;
	  String lineEnd = "\r\n";
	  String twoHyphens = "--";
	  String boundary =  "*****";
	   //------------------ CLIENT REQUEST
	   // open a URL connection to the Servlet
	   URL url = new URL(urlString);
	   // Open a HTTP connection to the URL
	   conn = (HttpURLConnection) url.openConnection();
	   // Allow Inputs
	   // Allow Outputs
	   // Don't use a cached copy.
	   // Use a post method.
	   conn.setRequestProperty("Connection", "Keep-Alive");
	   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
	   dos = new DataOutputStream( conn.getOutputStream() );
	   //JSONArray obj = new JSONArray();
	   JSONObject obj = new JSONObject();
	   try {
		   obj.put("first_name", firstName);
		   obj.put("last_name", lastName);
		   obj.put("email", email);
	   } catch(Exception ex) {
		   Log.e("Debug", "json data error in contact create: " + ex.getMessage(), ex);
	   dos.writeBytes(twoHyphens + boundary + lineEnd);
	   dos.writeBytes("Content-Disposition: form-data; name=\"contact\""+ lineEnd);
	   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	   // close streams
	   Log.e("Debug","File is written");
	  catch (MalformedURLException ex)
	       Log.e("Debug", "error: " + ex.getMessage(), ex);
	  catch (IOException ioe)
	       Log.e("Debug", "error: " + ioe.getMessage(), ioe);
	  //------------------ read the SERVER RESPONSE
	  try {
	        inStream = new DataInputStream ( conn.getInputStream() );
	        String str;
	        while (( str = inStream.readLine()) != null)
	        	response = str;
	            Log.e("Debug","Server Response(Campaign_Create) "+ str);
	  catch (IOException ioex){
	       Log.e("Debug", "error: " + ioex.getMessage(), ioex);
	  return response;

This is post demonstrates the client-side code of REST APIs in Android. The Server-side code for the Contact_Create functions is not shown. It is assumed while calling the Web services that the client is only familiar with Web service name, its input arguments and output values. That is why we have only focused on these things and to make it look that calling REST web services is very simple and easy.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.