Calling a REST web service from Android

I recently had the need to call a REST based web service from Android. I
searched the net for several days before finding the proper (and
easiest) way to do this. Hopefully I will save some of you the trouble.

First you will need to import all of the apache HttpClient libs. Then
you create the request and make the call, the result of which is a
String. In My example, I am merely making the call after the user
chooses to search for a specific value.

*** This example doesn’t launch the web service call within a separate thread, for the sake of readability. If doing this in a production app, you should most certainly use a non-UI thread to do the web service call. ***

package com.example.android;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class AndroidApp extends Activity {
	
	String URL = "http://the/url/here";
	String result = "";
	String deviceId = "xxxxx" ; 
	final String tag = "Your Logcat tag: ";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final EditText txtSearch = (EditText)findViewById(R.id.txtSearch);
        txtSearch.setOnClickListener(new EditText.OnClickListener(){
        	public void onClick(View v){txtSearch.setText("");}
    	});
        
        final Button btnSearch = (Button)findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {
				String query = txtSearch.getText().toString();
				callWebService(query);
				
			}
        });
        
    } // end onCreate()
    
    public void callWebService(String q){
    	HttpClient httpclient = new DefaultHttpClient();
		HttpGet request = new HttpGet(URL + q);
		request.addHeader("deviceId", deviceId);
		ResponseHandler handler = new BasicResponseHandler();
		try {
			result = httpclient.execute(request, handler);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown(); 
		Log.i(tag, result);
    } // end callWebService()
}

17 Responses to “Calling a REST web service from Android”

  1. Это мне не подходит. Кто еще, что может подсказать?…

    First you will need to import all of the apache HttpClient libs. Then you create the request and make […….

  2. Hey mate,

    I’ve got some code that extends on this basic idea with a class that is hopefully a bit more reusable – http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

  3. Thanks Luke! I had trouble finding info on how to do this as I was getting started and thought I would share what I learned. Your solution looks great!

  4. Hi mark, I am stuck in middle of a project do u know how to send xml as request like for authendication

    UserName>username.gmail.comPassword64312648dfyu454897</TokenId

    to the soap message

    <?xml version="1.0" encoding="utf-8"?
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd="http://www.w3.org/2001/XMLSchema&quot; xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/&quot;

    <AuthenticateUser xmlns="http://parkinghero.com/&quot;
    <clsAuthenticateAndGetUserProfileRequest

    UserName>stringstringstring</TokenID
    /clsCredentials
    /clsAuthenticateAndGetUserProfileRequest
    /AuthenticateUser
    /soap:Body
    /soap:Envelope

  5. Hi Kishore. My suggestion would be to ask your question on Stack Overflow, if you don’t get what you need from this:
    http://stackoverflow.com/questions/2559948/android-sending-xml-via-http-post-soap

  6. Hi, i’m using to program above to call my web service. but i encounter error on this part:
    public void callWebService(String q){
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL + q);
    request.addHeader(“deviceId”, deviceId);
    ResponseHandler handler = new BasicResponseHandler();
    try {
    result = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    Log.i(tag, result);
    } // end callWebService()
    }

    the was an error and cause the 2nd last } to error as well. wat has it gone wrong?

  7. H Jy. In the listing, there is a bogus being displayed. It isn’t in what is being posted into the blog, so it seems to be added by WP automatically. That could be the problem. That tag does not need to be in your code. Beyond that, I would need more information as to exactly what the error is, to tell you what is wrong.

  8. hi, thanks for replied… the error i hv is string cannot be resolved.
    the problem i have is it because it did not add some other things?

  9. Hi. Thanks for the nice post. but i have a confusion.
    Do you think the code should be
    ResponseHandler handler = new BasicResponseHandler();
    instead of
    ResponseHandler handler = new BasicResponseHandler();
    at line 52?
    Since Java is case sensitive, ‘s’ will call the ‘android.R’ instead of ‘java.lang.String’.

  10. You shouldn’t be making REST calls from an Activity (which may be killed at any moment if it’s not in the foreground) in the first place. You should use an Android Service.

  11. I am new to Android. Sorry about the question. I have created an application and it is using the SAXparser to retrieve the xml infromation from the Resfull web service. I am not using any HTTPclient. I have tested on the local network and it is working fine. Why do I need the HTTPclient? Thanks.

  12. I have a REST library called resting (http://code.google.com/p/resting)which can be used to invoke HTTP and HTTPS REST services with parameters and get the list of objects from HTTP response in a single step. Please take a look

  13. [...] found this resource online http://timewasted.net/?p=127. I think it may be exactly what I’m looking for, but I’ll have to check it out via my [...]

  14. NOOOOOOOOO! NO NO NO NO NO! DO NOT USE THIS EXAMPLE VERBATIM!!!

    Some of the code here might be useful for understanding how to make the HTTP request and parse the results but DO NOT do it like this! NEVER put ANY code that relies on slow components (network, database, file reading, etc) inside of your Activity thread! THIS is what causes “Application Not Responding” nearly all of the time. AND if your application dies (e.g. you got a call), you will not be able to always leave off from where your app was.

    Google had a decent discussion at I/O about ideas of how to do proper REST stuff with Android (no code though) http://www.youtube.com/watch?v=xHXn3Kg2IQE

  15. Hi, I have a question.
    I have many REST requests [around 20] to be used in my app. I have watched the valuable session in Google I/O mentioned above. My question is, which is the better approach. To have single service handling all the requests in single service? or to have a dedicated service for each of the requests?
    I have some of the requests that should be fired sequentially and some of them can be fired simultaneously.
    Any suggestions ?

  16. @Jouva, you are correct in many ways. While I don’t agree that the code should always be outside of the activity class, it should be contained within separate thread. This example doesn’t quite go far enough to explain the situation, however is rather intended to give a small and easy to read example of how to make the request itself.

    In my live app, I actually launch a thread to make the web service calls and show a progress dialog to the user. In my particular use case, I do not want to allow the user to interact with the screen while the service is running.

  17. @HK I think this would really depend on the use case for your app. In my production app, I have all request coming from a single class, but they are triggered from various activities and typically make calls where a very limited amount of data is returned. This is really the chatty vs chunky debate, but it really boils down to a design preference.