Click here to Skip to main content
Click here to Skip to main content
Technical Blog

WCF and Android: Part II

, 5 Apr 2012 Apache
Rate this:
Please Sign up or sign in to vote.
How to consume a JSON REST WCF service using Android.

Introduction

The first part of this series WCF and Android Part I describes how to setup a JSON REST WCF service. This post shows how to consume this service using Android.

Simple Webservice invokation

Android already comes with a ready to use HTTP-client located in the package org.apache.http.client.

HttpParams httpParams = new BasicHttpParams();
ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(httpParams, new SchemeRegistry()); 
HttpClient client = new DefaultHttpClient(connMgr, httpParams);

Therefore a simple webservice invocation looks as follows:

HttpGet get = new HttpGet("http://requesturi/method");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();

JSON serialization

Simple parameters can be passed in the URL but more complex objects are likely passed in the http body using the POST method. For modern and fast webservices it is common to use JSON for data serialization. Android has some JSON features built in but Google GSON provides a very flexible way to serialize and deserialize JSON objects, even for arbitrary object types. Download the library and include it in your build-path. The first step is to create a GsonBuilder, where some de-/serialization options can be specified.

GsonBuilder gson = new GsonBuilder()
  .registerTypeAdapter(Date.class, new DateSerializer())
  .serializeNulls()
  .setDateFormat(DateFormat.LONG)
  .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
  .setPrettyPrinting()
  .create();

Beside some others this example attaches a custom DateSerializer (thanks to Benjii Me) to be able to read WCF serialized DateTime values. That's all you need to do. Serialization now looks as follows:

String jsonString = gson.toJson(myObject);

and deserialization very similar:

MyObjectType myObj = gson.fromJson(jsonString, MyObjectType.class);

Webservice invokation with JSON-POST arguments

Every webservice requests only allows a single JSON object in the HTTP-body, therefore if multiple arguments are required they need to be wrapped in a single JSON object and the WCF service contract needs to be aware of it (BodyStyle=WebMessageBodyStyle.WrappedRequest).

Once the webservice is aware of the BodyStyle the client side is quite straight forward. Create a Map from name to object, add all objects with the name of the webservice parameter and serialize the whole map:

HashMap<String, Object> postParameters = new HashMap<String, Object>();
postParameters.put("param1", objParam1);
postParameters.put("param2", objParam2);
postParameters.put("param3", objParam3);
gson.toJson(postParameters);

A complete webservice call looks as follows:

HttpPost post = new HttpPost(requestUri);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
 
String jsonParameters = gson.toJson(postParameters);
post.setEntity(new StringEntity(jsonParameters));      
      
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();

Reading the webservice response

Assuming that the webservice was called successful a HttpEntity is returned. This entity can be easily converted to the corresponding object as shown above. The only difficulty is to convert the HttpEntity to a JSON string:

gson.fromJson(convertStreamToString(entity.getContent()), MyObjectType.class);
 
public static String convertStreamToString(InputStream is) {
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();
}

Original post blogged on b2evolution.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

deveck
Student
Austria Austria
No Biography provided

Comments and Discussions

 
QuestionPassing Parameter with slash "/" PinmemberShan-Bala23-Oct-14 5:51 
QuestionError scheme http is not register Pinmemberchirag solanki 9085113-Sep-14 21:47 
AnswerRe: Error scheme http is not register Pinmemberchirag solanki 9085113-Sep-14 22:32 
Questionjavalang.illegal state exception:Scheme "http" not registered PinmemberMember 1035541925-May-14 19:42 
GeneralMy vote of 3 PinmemberMember 1029875022-Mar-14 22:36 
QuestionProper link to Part I Pinmembersuhani266-Nov-13 21:03 
QuestionTwo more pieces: (a) Encrypt .NET, decrypt Android, (b) XmlDocument parsing [modified] Pinmemberdevvvy25-Jan-13 17:15 
GeneralMy vote of 4 Pinmemberpedibär5-Nov-12 22:10 
QuestionLink to Part I broken Pinmembermilter00018-Sep-12 20:55 
AnswerRe: Link to Part I broken PinmemberCorke Ecratius12-Nov-12 10:43 
QuestionHope for code Pinmemberttssrs6-Sep-12 0:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 5 Apr 2012
Article Copyright 2012 by deveck
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid