title: Call Java servlet from Android
body: <p>I'm trying to get the output from a servlet on an Android phone.</p>
  
  <p>This is my servlet:</p>
  
  <pre><code>    /*
       * To change this template, choose Tools | Templates
       * and open the template in the editor.
       */
      package main;
  
      import java.io.IOException;
      import java.io.PrintWriter;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
  
      /**
       *
       * @author Bert Verhelst &lt;verhelst_bert@hotmail.com&gt;
       */
      public class servlet1 extends HttpServlet {
  
          /**
           * Processes requests for both HTTP &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt; methods.
           * @param request servlet request
           * @param response servlet response
           * @throws ServletException if a servlet-specific error occurs
           * @throws IOException if an I/O error occurs
           */
          protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              response.setContentType("text/html;charset=UTF-8");
              PrintWriter out = response.getWriter();
              out.println("&lt;html&gt;");
              out.println("&lt;head&gt;");
              out.println("&lt;title&gt;Servlet servlet1&lt;/title&gt;");
              out.println("&lt;/head&gt;");
              out.println("&lt;body&gt;");
              out.println("&lt;h1&gt;processing...&lt;/h1&gt;");
              out.println("&lt;/body&gt;");
              out.println("&lt;/html&gt;");
          }
  
          // &lt;editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."&gt;
          /**
           * Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method.
           * @param request servlet request
           * @param response servlet response
           * @throws ServletException if a servlet-specific error occurs
           * @throws IOException if an I/O error occurs
           */
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              processRequest(request, response);
              PrintWriter out = response.getWriter();
              out.println("&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
                      + "Transitional//EN\"&gt;\n"
                      + "&lt;html&gt;\n"
                      + "&lt;head&gt;&lt;title&gt;Hello WWW&lt;/title&gt;&lt;/head&gt;\n"
                      + "&lt;body&gt;\n"
                      + "&lt;h1&gt;doget...&lt;/h1&gt;\n"
                      + "&lt;/body&gt;&lt;/html&gt;");
          }
  
          /**
           * Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method.
           * @param request servlet request
           * @param response servlet response
           * @throws ServletException if a servlet-specific error occurs
           * @throws IOException if an I/O error occurs
           */
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              processRequest(request, response);
              PrintWriter out = response.getWriter();
              out.println("&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
                      + "Transitional//EN\"&gt;\n"
                      + "&lt;html&gt;\n"
                      + "&lt;head&gt;&lt;title&gt;Hello WWW&lt;/title&gt;&lt;/head&gt;\n"
                      + "&lt;body&gt;\n"
                      + "&lt;h1&gt;dopost...&lt;/h1&gt;\n"
                      + "&lt;/body&gt;&lt;/html&gt;");
          }
  
          /**
           * Returns a short description of the servlet.
           * @return a String containing servlet description
           */
          @Override
          public String getServletInfo() {
              return "Short description";
          }// &lt;/editor-fold&gt;
      }
  </code></pre>
  
  <p>This is my Android main page:</p>
  
  <pre><code>     package be.smarttelecom.MyTest;
  
       import android.app.Activity;
       import android.os.Bundle;
       import android.widget.TextView;
  
       public class Main extends Activity {
           /** Called when the activity is first created. */
           @Override
           public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.main);
               TextView output = (TextView) findViewById(R.id.output);
               try {
                   output.append("starting\n");
                   RestClient client = new  RestClient("http://10.0.0.188:8084/Servlet_1/servlet1");
  
                   try {
                       client.Execute(RequestMethod.GET);
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
  
                   output.append("after execute\n");
  
                   String response = client.getResponse();
                   output.append("class - " + response  +  "\n" );
                   output.append(response);
                   output.append("done\n");
               }
               catch (Exception ex) {
                   output.append("error: " + ex.getMessage() + "\n" + ex.toString() +  "\n");
               }
           }
       }
  </code></pre>
  
  <p>And finally we have the RestClient:</p>
  
  <pre><code>     package be.smarttelecom.MyTest;
  
       import java.io.BufferedReader;
       import java.io.IOException;
       import java.io.InputStream;
       import java.io.InputStreamReader;
       import java.util.ArrayList;
  
       import org.apache.http.HttpEntity;
       import org.apache.http.HttpResponse;
       import org.apache.http.NameValuePair;
       import org.apache.http.client.ClientProtocolException;
       import org.apache.http.client.HttpClient;
       import org.apache.http.client.entity.UrlEncodedFormEntity;
       import org.apache.http.client.methods.HttpGet;
       import org.apache.http.client.methods.HttpPost;
       import org.apache.http.client.methods.HttpUriRequest;
       import org.apache.http.impl.client.DefaultHttpClient;
       import org.apache.http.message.BasicNameValuePair;
       import org.apache.http.protocol.HTTP;
  
       public class RestClient {
           private ArrayList &lt;NameValuePair&gt; params;
           private ArrayList &lt;NameValuePair&gt; headers;
  
           private String url;
  
           private int responseCode;
           private String message;
  
           private String response;
  
           public String getResponse() {
               return response;
           }
  
           public String getErrorMessage() {
               return message;
           }
  
           public int getResponseCode() {
               return responseCode;
           }
  
           public RestClient(String url)
           {
               this.url = url;
               params = new ArrayList&lt;NameValuePair&gt;();
               headers = new ArrayList&lt;NameValuePair&gt;();
           }
  
           public void AddParam(String name, String value)
           {
               params.add(new BasicNameValuePair(name, value));
           }
  
           public void AddHeader(String name, String value)
           {
               headers.add(new BasicNameValuePair(name, value));
           }
  
           public void Execute(RequestMethod method) throws Exception
           {
               switch(method) {
                   case GET:
                   {
                       //add parameters
                       String combinedParams = "";
                       if(!params.isEmpty()){
                           combinedParams += "?";
                           for(NameValuePair p : params)
                           {
                               String paramString = p.getName() + "=" + p.getValue();
                               if(combinedParams.length() &gt; 1)
                               {
                                   combinedParams  +=  "&amp;" + paramString;
                               }
                               else
                               {
                                   combinedParams += paramString;
                               }
                           }
                       }
  
                       HttpGet request = new HttpGet(url + combinedParams);
  
                       //add headers
                       for(NameValuePair h : headers)
                       {
                           request.addHeader(h.getName(), h.getValue());
                       }
                       executeRequest(request, url);
                       break;
                   }
  
                   case POST:
                   {
                       HttpPost request = new HttpPost(url);
  
                       //add headers
                       for(NameValuePair h : headers)
                       {
                           request.addHeader(h.getName(), h.getValue());
                       }
  
                       if(!params.isEmpty()){
                           request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                       }
  
                       executeRequest(request, url);
                       break;
                   }
               }
           }
  
           private void executeRequest(HttpUriRequest request, String url)
           {
               HttpClient client = new DefaultHttpClient();
  
               HttpResponse httpResponse;
  
               try {
                   httpResponse = client.execute(request);
                   responseCode = httpResponse.getStatusLine().getStatusCode();
                   message = httpResponse.getStatusLine().getReasonPhrase();
  
                   HttpEntity entity = httpResponse.getEntity();
  
                   if (entity != null) {
                       InputStream instream = entity.getContent();
                       response = convertStreamToString(instream);
  
                       // Closing the input stream will trigger connection release
                       instream.close();
                   }
               }
               catch (ClientProtocolException e)  {
                   client.getConnectionManager().shutdown();
                   e.printStackTrace();
               } catch (IOException e) {
                   client.getConnectionManager().shutdown();
                   e.printStackTrace();
               }
           }
  
           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();
           }
       }
  </code></pre>
  
  <p>Unfortunately this doesn't work. Here is what I get for output (null),</p>
  
  <p><img src="https://i.stack.imgur.com/KFo82.png" alt="Screenshot of "></p>
  
  <p>What am I doing wrong?</p>
  
  <p>I request the DoGet method of my servlet and convert the output to a string, but it appears to be empty.</p>
  
  <p>I allowed the Internet connection in the manifest file just after the closing bracket of application,</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
  </code></pre>