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.
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()
}
Categories: Uncategorized
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/
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!