从 Android 调用 Java servlet

Posted

技术标签:

【中文标题】从 Android 调用 Java servlet【英文标题】:Call Java servlet from Android 【发布时间】:2011-03-16 10:42:30 【问题描述】:

我正在尝试从 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),

我做错了什么?

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

我在应用程序右括号之后的清单文件中允许互联网连接,

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

【问题讨论】:

如果您从浏览器访问 servlet,您会得到预期的结果吗?此外,您的 doGet() 调用 processRequest,它执行 out.close(),而 doGet 尝试在关闭的流上写入更多 HTML(从不关闭 servlet 中的输出流)。 调用是否到达了 Servlet ?服务器看到正在发送什么?服务器发回什么? 【参考方案1】:

Romain Hippeau 在评论中写道:

调用是否会到达 servlet?服务器看到正在发送什么?服务器发回什么?

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

【讨论】:

以上是关于从 Android 调用 Java servlet的主要内容,如果未能解决你的问题,请参考以下文章

将图像从android上传到java servlet并保存

从其他项目调用java servlet [重复]

从 Java GUI 应用程序调用 servlet?

httpClient post 调用从 servlet 失败并出现错误 java.lang.NoSuchMethodError:

从android向servlet发送一个字符串

无法将图像文件从 Android 应用程序发布到托管在 Tomcat 上的 Java servlet