Click here to Skip to main content
15,883,854 members
Articles / Mobile Apps / Android

WCF and Android: Part II

Rate me:
Please Sign up or sign in to vote.
3.67/5 (9 votes)
5 Apr 2012Apache2 min read 91K   23   11
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 Invocation

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

C#
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:

C#
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.

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

Besides 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:

C#
String jsonString = gson.toJson(myObject);

and deserialization very similar:

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

Webservice Invocation 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:

C#
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:

C#
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:

C#
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


Written By
Student
Austria Austria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionPassing Parameter with slash "/" Pin
Shan-Bala23-Oct-14 4:51
Shan-Bala23-Oct-14 4:51 
QuestionError scheme http is not register Pin
chirag solanki 9085113-Sep-14 20:47
chirag solanki 9085113-Sep-14 20:47 
AnswerRe: Error scheme http is not register Pin
chirag solanki 9085113-Sep-14 21:32
chirag solanki 9085113-Sep-14 21:32 
Questionjavalang.illegal state exception:Scheme "http" not registered Pin
Member 1035541925-May-14 18:42
Member 1035541925-May-14 18:42 
GeneralMy vote of 3 Pin
Member 1029875022-Mar-14 21:36
Member 1029875022-Mar-14 21:36 
QuestionProper link to Part I Pin
Suhani Mody6-Nov-13 20:03
Suhani Mody6-Nov-13 20:03 
QuestionTwo more pieces: (a) Encrypt .NET, decrypt Android, (b) XmlDocument parsing Pin
devvvy25-Jan-13 16:15
devvvy25-Jan-13 16:15 
GeneralMy vote of 4 Pin
pedibär5-Nov-12 21:10
pedibär5-Nov-12 21:10 
QuestionLink to Part I broken Pin
milter00018-Sep-12 19:55
milter00018-Sep-12 19:55 
AnswerRe: Link to Part I broken Pin
Matúš Michalov12-Nov-12 9:43
Matúš Michalov12-Nov-12 9:43 
QuestionHope for code Pin
ttssrs5-Sep-12 23:57
ttssrs5-Sep-12 23:57 

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

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