Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Java servlet from Android

I'm trying to get the output from a servlet on an Android phone.

This is my servlet:

    /*
     * 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 <[email protected]>
     */
    public class servlet1 extends HttpServlet {

        /**
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> 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("<html>");
            out.println("<head>");
            out.println("<title>Servlet servlet1</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>processing...</h1>");
            out.println("</body>");
            out.println("</html>");
        }

        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /**
         * Handles the HTTP <code>GET</code> 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
                    + "Transitional//EN\">\n"
                    + "<html>\n"
                    + "<head><title>Hello WWW</title></head>\n"
                    + "<body>\n"
                    + "<h1>doget...</h1>\n"
                    + "</body></html>");
        }

        /**
         * Handles the HTTP <code>POST</code> 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
                    + "Transitional//EN\">\n"
                    + "<html>\n"
                    + "<head><title>Hello WWW</title></head>\n"
                    + "<body>\n"
                    + "<h1>dopost...</h1>\n"
                    + "</body></html>");
        }

        /**
         * Returns a short description of the servlet.
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    }

This is my Android main page:

     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");
             }
         }
     }

And finally we have the RestClient:

     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 <NameValuePair> params;
         private ArrayList <NameValuePair> 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<NameValuePair>();
             headers = new ArrayList<NameValuePair>();
         }

         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() > 1)
                             {
                                 combinedParams  +=  "&" + 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();
         }
     }

Unfortunately this doesn't work. Here is what I get for output (null),

Screenshot of

What am I doing wrong?

I request the DoGet method of my servlet and convert the output to a string, but it appears to be empty.

I allowed the Internet connection in the manifest file just after the closing bracket of application,

<uses-permission android:name="android.permission.INTERNET" />
like image 562
Berty Avatar asked Jul 15 '10 14:07

Berty


1 Answers

Romain Hippeau wrote in a comment:

Does the call ever get to the servlet? What does the server see is being sent? What is the server sending back?

That was the problem! I disabled my firewall and now it works :)

like image 55
Berty Avatar answered Sep 21 '22 23:09

Berty