从Android调用Java servlet

时间:2010-07-15 14:18:44

标签: java android servlets httpclient

我正在尝试从Android手机上获取servlet的输出。

这是我的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 <verhelst_bert@hotmail.com>
     */
    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>
    }

这是我的Android主页:

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

最后我们有了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();
         }
     }

不幸的是,这不起作用。这是我得到的输出(null),

Screenshot of

我做错了什么?

我请求我的servlet的DoGet方法并将输出转换为字符串,但它似乎是空的。

我在应用程序的结束括号后面的清单文件中允许了Internet连接,

<uses-permission android:name="android.permission.INTERNET" />

1 个答案:

答案 0 :(得分:3)

Romain Hippeau在评论中写道:

  

调用是否可以访问servlet?服务器看到的是什么?什么是服务器发回?

那就是问题!我禁用了我的防火墙,现在它可以工作:)