How-To: Android Client – Server designs

Applications are usually designed so that a Server provides a service to a Client. Choosing an implementation depends on the requirements. Inside this article I will be explaining three implementation types:

  • SOAP
  • Servlet
  • JSON

I will use the Android application which was developed inside my previous post.

SOAP

Simple Object Access Protocol is basically designed to provide a lightweight mechanism to exchange data in a XML format. Setting up a SOAP web service isn’t al that difficult. There is a disadvantage of using SOAP, and that’s overhead. Because there is no default SOAP support inside the Android library, I will be using kSOAP.


So lets set-up an implementation.

  1. Create a server implementation
  2.      public class Hello {
         
              public String sayHello(String name) {
                   return "Hello " + name;
              }
         }
  3. Create an Android implementation
  4. Create a call to the server
  5.      private void callService(SoapSerializationEnvelope envelope) {
              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

              // Call the URL
              try {
                   androidHttpTransport.call(SOAP_ACTION, envelope);
              } catch (IOException e) {
                   display("Error:" + e.getClass().getName() + ": " + e.getMessage());
              } catch (XmlPullParserException e) {
                   display("Error:" + e.getClass().getName() + ": " + e.getMessage());
              }
         }
  6. Handle the response
  7.      private SoapPrimitive getResultFromService(String text) {
              SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

              request.addProperty("name", text);

              envelope.setOutputSoapObject(request);

              callService(envelope);

              SoapPrimitive result = null;
              try {
                   result = (SoapPrimitive) envelope.getResponse();
              } catch (SoapFault e) {
                   display("Error:" + e.getClass().getName() + ": " + e.getMessage());
              }
              return result;
         }

Download source code BackEndWSDL [5kB] and FrondEndWSDL [114kB]

Servlet

The most simple form of exchanging data is by way of HTTP(s) with the use of Java Servlets. There’s no need to serialize to/from XML, so it can be a real time saver.

So lets set-up an implementation.

  1. Create a server implementation
  2.      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String text = "";
              StringBuffer sb = new StringBuffer();
              try {
                   BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                   String line = reader.readLine();
                   while (line != null) {
                        sb.append(line);
                        line = reader.readLine();
                   }
                   if (sb.length() != 0) {
                        text = sb.toString();
                   }
              } catch (Exception e) {
              }

              response.setContentType("text/plain");
              response.setHeader("Cache-Control", "no-cache");

              if (StringUtils.isNotEmpty(text)) {
                   response.getWriter().write(HELLO_STRING + text);
              } else {
                   response.getWriter().write(HELLO_STRING);
              }

         }
  3. Create an Android implementation
  4. Create a call to the server
  5.      private InputStream callService(String text) {
              InputStream in = null;
             
              try {
                   URL url = new URL(SERVLET_URL);
                   URLConnection conn = url.openConnection();

                   
                   HttpURLConnection httpConn = (HttpURLConnection) conn;
                   httpConn.setRequestMethod("POST");
                   httpConn.setDoInput(true);
                   httpConn.setDoOutput(true);
                   httpConn.connect();
                   
                   DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream());
                   
                   dataStream.writeBytes(text);
                   dataStream.flush();
                dataStream.close();

                int responseCode = httpConn.getResponseCode();
                   if (responseCode == HttpURLConnection.HTTP_OK) {
                        in = httpConn.getInputStream();
                   }
              } catch (Exception ex) {
                   display("Error: Not not connect");
              }
              return in;
         }
  6. Handle the response
  7.      private String getResultFromServlet(String text) {
              String result = "";
              InputStream in = callService(text);
              if(in!=null) {
                   result= convertStreamToString(in);
              } else {
                   result = "Error: Service not returning result";
              }
              return result;
         }
         private 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();
         }

Download source code BackEndServlet [242kB] and FrondEndServlet [16kB]

JSON

So SOAP has the advantage of using a model, and HTTP(s) has the advantage of being simple. There is an implementation that uses both. JavaScript Object Notation is a light-weight data-interchange format, think of it as XML on a diet

So lets set-up an implementation.

  1. Create a server implementation
  2.      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String text = "";
              StringBuffer sb = new StringBuffer();
              try {
                   BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                   String line = reader.readLine();
                   while (line != null) {
                        sb.append(line);
                        line = reader.readLine();
                   }
                   if (sb.length() != 0) {
                        text = sb.toString();
                   }
              } catch (Exception e) {
                   System.out.println(e);
              }

              response.setContentType("text/plain");
              response.setHeader("Cache-Control", "no-cache");
             
              JsonObject jsonObj=new JsonObject();
             
              if (StringUtils.isNotEmpty(text)) {
                   jsonObj.addProperty(JSON_KEY, HELLO_STRING + text);
              } else {
                   jsonObj.addProperty(JSON_KEY, HELLO_STRING);
              }
              PrintWriter out = response.getWriter();
              out.println(jsonObj);
         }
  3. Create an Android implementation
  4. Create a call to the server
  5.      private InputStream callService(String text) {
              InputStream in = null;

              try {
                   URL url = new URL(SERVLET_URL);
                   URLConnection conn = url.openConnection();

                   HttpURLConnection httpConn = (HttpURLConnection) conn;
                   httpConn.setRequestMethod("POST");
                   httpConn.setDoInput(true);
                   httpConn.setDoOutput(true);
                   httpConn.connect();

                   DataOutputStream dataStream = new DataOutputStream(conn
                             .getOutputStream());

                   dataStream.writeBytes(text);
                   dataStream.flush();
                   dataStream.close();

                   int responseCode = httpConn.getResponseCode();
                   if (responseCode == HttpURLConnection.HTTP_OK) {
                        in = httpConn.getInputStream();
                   }
              } catch (Exception ex) {
                   display("Error: Not not connect");
              }
              return in;
         }
  6. Handle the response
  7.      private String getResultFromServlet(String text) {
              String result = "";

              InputStream in = callService(text);
              if (in != null) {
                   JSONObject jsonResponse;
                   try {
                        jsonResponse = new JSONObject(convertStreamToString(in));
                        result = jsonResponse.getString("output");
                   } catch (JSONException e) {
                        result = "Error: JSON Object couldn't be made";
                   }
              } else {
                   result = "Error: Service not returning result";
              }
              return result;
         }
              private 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) {
              } finally {
                   try {
                        is.close();
                   } catch (IOException e) {
                        e.printStackTrace();
                   }
              }
              return sb.toString();
         }

Download source code BackEndJSON [399kB] and FrondEndJSON [15kB]

  1. M V UTTAM TEJ
    hi just now i download and try to execute ways of accessing servlet.But i had problem that the value of reader.readLine in android code is showing as "NULL" ........i am not getting output what is the reason for it.....................
  2. itsakv
    Hi i have tried webservice and servlet communication. both are not working. servet communication gives following error when you click the button: Error:Service not returning result
  3. Victor
    I have changed the IP address to my computer IP 192.168.1.4 and I have changed the port number to 8080 and it gives me an error message: Error:Service not returning result. What else could be changed? Thanks.
  4. Victor
    I have changed the IP address to my computer IP 192.168.1.4 and I have changed the port number to 8080 and it gives me an error message: Error:Service not returning result. What else could be changed? Thanks.
  5. Victor
    Forgot to mention that I am using the servlet code. Thanks.
  6. Parmesh
    This is very helpful tutorial, i have successfully worked for Servlet and Soap...thnx
  7. TTT
    I added your project into my eclipse, but it has some error: the library javax.servlet is not found.
  8. W.Elsinga
    Are you using maven?.
  9. Christopher
    I got a few problems using the example "servlet", i am using andorid 4.03 and tomcat7, a few threads suggest i have to run network in a seperate thread, the code works fine if i run the client in a console "and it is not a network related bug" update?
  10. W.Elsinga
    UI and network related actions should be running on different Threads ever since honeycomb was introduced. Try to connect to the server on a different Thread.
  11. Shree
    I used the servlet example and I am getting the error as Error:Service not returning result. I am not able to recognize the problem. May I know what needs to be done ?

Leave a Reply

*

captcha *