How to Connect Android Client to a Java Servlet

Author: Veeresh Rudrappa. Date: March 2, 2013

In this blog I'll show how to host a Java Servlet in Apache Tomcat 7.0, build a basic android APP and then establishing communication between the two. I have come up with a basic android app "Double Me" for this tutorial, which just sends an integer to server and the server doubles it and returns it back to the android app.

Firstly, you would have to set up your development environment. Install the following software's on your machine. I developed this tutorial on Ubuntu, but all of the below listed Software's are available even for windows.

Let us first start with creating a Java Servlet.
Step 1: In your Eclipse go to File > New > Project > Web > Dynamic Web Project > next.

Dynamic Web Project

Step 2: Name your Project and select Apache Tomcat v7.0 as the target runtime and click finish.

Target Runtime

Step 3: Now right click on project > New > Other > Web > Servelt. Name the Servlet as DoubleMeServlet.

Create Servlet

Replace the Code in the Servlet with the code below.
                                        import java.io.IOException;
                                        import java.io.OutputStreamWriter;

                                        import javax.servlet.ServletException;
                                        import javax.servlet.ServletInputStream;
                                        import javax.servlet.annotation.WebServlet;
                                        import javax.servlet.http.HttpServlet;
                                        import javax.servlet.http.HttpServletRequest;
                                        import javax.servlet.http.HttpServletResponse;

                                        @WebServlet("/DoubleMeServlet")
                                        public class DoubleMeServlet extends HttpServlet {
	                                        private static final long serialVersionUID = 1L;

	                                        public DoubleMeServlet() {
                                                super();

                                            }

	                                        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		                                        response.getOutputStream().println("Hurray !! This Servlet Works");
		
	                                        }

	                                        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
                                                try {
                                                    int length = request.getContentLength();
                                                    byte[] input = new byte[length];
                                                    ServletInputStream sin = request.getInputStream();
                                                    int c, count = 0 ;
                                                    while ((c = sin.read(input, count, input.length-count)) != -1) {
                                                        count +=c;
                                                    }
                                                    sin.close();
        
                                                    String recievedString = new String(input);
                                                    response.setStatus(HttpServletResponse.SC_OK);
                                                    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
  	
                                                    Integer doubledValue = Integer.parseInt(recievedString) * 2;
            
			                                        writer.write(doubledValue.toString());
                                                    writer.flush();
                                                    writer.close();

        

                                                } catch (IOException e) {
           
        	
        	                                        try{
        		                                        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        		                                        response.getWriter().print(e.getMessage());
        		                                        response.getWriter().close();
                                                    } catch (IOException ioe) {
                                                    }
                                                }	
                                                }

                                        }

                                        

Step 4: Right click on Servlet project > Run as > Run on Server. Run on Server Dialog should pop up. Select "Manually define a new server" and also Tomcat v7.0 under server type." Before that make sure your tomcat server is up and running. Open your web browser and type http://localhost:8080. You should see a default page displayed by tomcat server.

Run On Server
Now let us test if the Servlet is hosted properly. I have added a simple response message for the get operation on the Servlet. Go to this link on your web browser. http://localhost:8080/MyServletProject/DoubleMeServlet , update the project name and the Servlet name if you have changed it. If everything goes right, you should see this response on your browser : "Hurray !! This Servlet Works".

Step 5: Now we are ready start building our Android App.
In your eclipse go to File > New > Project > Android Project > next > give a project name > next > Select android target ( I opted for android 3.2 api 13) > next > Name your application > com.app.myapp as package name > Name your activity as DoubleMe > slect sdk 13 > finish.

Step 6: Replace the DoubleMeActivity.java with the code below.

                                        package com.app.myapp;

                                        import java.io.BufferedReader;
                                        import java.io.InputStreamReader;
                                        import java.io.OutputStreamWriter;
                                        import java.net.URL;
                                        import java.net.URLConnection;
                                        import android.app.Activity;
                                        import android.os.Bundle;
                                        import android.util.Log;
                                        import android.view.View;
                                        import android.view.View.OnClickListener;
                                        import android.widget.Button;
                                        import android.widget.EditText;

                                        public class DoubleMeActivity extends Activity implements OnClickListener {
	
	                                        EditText inputValue=null;
	                                        Integer doubledValue =0;
	                                        Button doubleMe;
	
                                            @Override
                                            public void onCreate(Bundle savedInstanceState) {
                                                super.onCreate(savedInstanceState);
                                                setContentView(R.layout.calculate);

                                                inputValue = (EditText) findViewById(R.id.inputNum);
                                                doubleMe = (Button) findViewById(R.id.doubleme);
        
                                                doubleMe.setOnClickListener(this);
                                            }

	                                        @Override
	                                        public void onClick(View v) {
		
		                                        switch (v.getId()){
		                                        case R.id.doubleme:
			
			                                          new Thread(new Runnable() {
				                                            public void run() {

						                                        try{
							                                        URL url = new URL("http://10.0.2.2:8080/MyServletProject/DoubleMeServlet");
							                                        URLConnection connection = url.openConnection();
							
							                                        String inputString = inputValue.getText().toString();
							                                        //inputString = URLEncoder.encode(inputString, "UTF-8");

							                                        Log.d("inputString", inputString);
							
							                                        connection.setDoOutput(true);
							                                        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
							                                        out.write(inputString);
							                                        out.close();
							
							                                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
							
							                                        String returnString="";
							                                        doubledValue =0;
							
							                                        while ((returnString = in.readLine()) != null) 
							                                        {
								                                        doubledValue= Integer.parseInt(returnString);
							                                        }
							                                        in.close();
						
							
							                                        runOnUiThread(new Runnable() {
							                                             public void run() {

							    	                                         inputValue.setText(doubledValue.toString());

							                                            }
							                                        });

							                                        }catch(Exception e)
							                                        {
								                                        Log.d("Exception",e.toString());
							                                        }

				                                            }
				                                          }).start();

			                                        break;
			                                        }
		                                        }
		
	                                        }

                                    

Step 7: In your project tree , go to layout and rename the main.xml to calculate.xml and replace its content with the code below.

                                    
                                    < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                  android:layout_width="fill_parent"
                                                  android:layout_height="fill_parent"
                                                  android:orientation="vertical" >

                                        < TextView
                                            android:id="@+id/textView1"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:text="Enter your number to be doubled.">< /TextView>

                                        < EditText
                                            android:id="@+id/inputNum"
                                            android:layout_width="match_parent"
                                            android:layout_height="wrap_content">
                                        < /EditText>

                                        < Button
                                            android:id="@+id/doubleme"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:text="Double Me">< /Button>
                                    < /LinearLayout>
                                      

Step 8: In your AndroidManifest.xml add the line < uses-permission android:name="android.permission.INTERNET"/>.

                                    
                                    
	                                    
                                        

                                        
                                            
                                                
                                                    

                                                    
                                                
                                            
                                        

                                    
                                      

Step 9: Now let us start the android emulator. Go to Windows > AVD Manager > New . Select some name for your device, Select target as Android 3.2, API 13 and click on create AVD. Be patient, it could take 4 to 5 minutes for your android to boot up. Once you see the android home screen on your emulator, right click on your project > run as > Android application.

Step 10: That's it. Let us now test our android app. Enter some number and click on double me button. If everything goes fine you will see your number getting doubled.

Android Emulator
Android Emulator
Hope this Helps :)
comments powered by Disqus