How-to: Android as a RESTful Client
This is a how-to focused on creating a RESTful java object at Android. I’ve used HTTPClient, HTTPEntry, HTTPGet, HTTPResponse, JSONArray and JSONObject classes. I think it’ll be useful if we need to use a web-service from client application.
I’ve implemented a simple Java Object called RestClient which connects to a given Rest-JSON service. After connection, this object prints response content. Using this content, a JSONObject created. Then, RestClient prints the JSONObject’s content, parses all values of this object and prints them as well. And as a last job, RestClient pushes a sample value to the JSONObject.
I’ve uploaded RestClient. Hope it’ll be useful.
P.s: To get access to internet at Android, following field must be included to AndroidManifest.xml file of the project.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>package praeda.muzikmekan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class RestClient { private static String convertStreamToString(InputStream is) { /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */ BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } /* This is a test function which will connects to a given * rest service and prints it's response to Android Log with * labels "Praeda". */ public static void connect(String url) { HttpClient httpclient = new DefaultHttpClient(); // Prepare a request object HttpGet httpget = new HttpGet(url); // Execute the request HttpResponse response; try { response = httpclient.execute(httpget); // Examine the response status Log.i("Praeda",response.getStatusLine().toString()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); String result= convertStreamToString(instream); Log.i("Praeda",result); // A Simple JSONObject Creation JSONObject json=new JSONObject(result); Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>"); // A Simple JSONObject Parsing JSONArray nameArray=json.names(); JSONArray valArray=json.toJSONArray(nameArray); for(int i=0;i<valArray.length();i++) { Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n" +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">"); } // A Simple JSONObject Value Pushing json.put("sample key", "sample value"); Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>"); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
January 28th, 2009 at 02:21
Wow! Thank you very much!
I always wanted to write in my blog something like that. Can I take part of your post to my site?
Of course, I will add backlink?
Regards, Timur I. Alhimenkov
January 28th, 2009 at 02:32
Of course you can use the content with a link. Glad that you appreciate my work : )
March 26th, 2009 at 09:38
Hi, Its great job. Thanks for ur support.
May 10th, 2009 at 19:52
Thanks for posting this, it’s very useful!
I found that reusing HttpClient across many requests greatly improved the performance of my application, but otherwise the code I’m using looks pretty much like this.
May 11th, 2009 at 23:54
[...] Android libraries include the Apache HTTP library, which is quite good (if a little verbose). This HTTP & JSON example is great, and as I discovered if you reuse the HttpClient object your app will load lots of data [...]
June 30th, 2009 at 09:15
Thank you very much for posting this
July 16th, 2009 at 10:00
Thanks for this valuable information.
ellerine saglik. cok guzel anlatmissin.
Omer
July 27th, 2009 at 17:22
I’m trying to add two number using web service in C# and android client. Can you help me with this?
If you have some simple example, full project please
Thanks
September 9th, 2009 at 11:37
Great work! Under what license is this? is it ok to reuse your code in my own projects?
September 9th, 2009 at 15:03
Please feel free to reuse the code.
September 9th, 2009 at 15:31
@Milos We are no longer developing our android application (see here), and the team got separated at late June. So, unfortunately we can’t help you. Sorry for the late response.
November 5th, 2009 at 13:44
Hi,
i have implemented this with android application. i have server running at 192.X.X.X:8080, but when I try to connect this, like httpClient.execute(httpPostmethod), where httpPostmethod has url- “http://192.X.X.X:8080/AndroidGH/Health/registe”, this gives me exception : connection to http://192.X.X.X:8080 is refused?
Can any body help on this?…..
January 8th, 2010 at 12:46
Thank dude!At the end i ve found useful code of android
January 10th, 2010 at 12:50
Thank. I will use your article to resolve my problems.
January 14th, 2010 at 15:25
Thank you for this.
Just a comment : it’s not useful to create and use the convertStreamToString method because httpClient.execute(HttpUriRequest, ResponseHandler) can make that for you. An example :
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(”you_url”);
ResponseHandler handler = new BasicResponseHandler();
//you result will be String :
String result = httpclient.execute(request, handler);
This method is simplest, and use the library…
January 14th, 2010 at 15:31
A problem with my comment : the ResponseHandler class have to be initiated with String :
ResponseHandler”String” (replace quotes with higher and less than signs)