代码之家  ›  专栏  ›  技术社区  ›  Berty

从Android调用Java servlet

  •  5
  • Berty  · 技术社区  · 14 年前

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

    这是我的servlet:

    。/*
    *要更改此模板,请选择“工具”“模板”
    *并在编辑器中打开模板。
    */
    包装主体;
    
    导入java.io.ioexception;
    导入java.io.printwriter;
    导入javax.servlet.servletexception;
    导入javax.servlet.http.http servlet;
    导入javax.servlet.http.httpservletrequest;
    导入javax.servlet.http.httpservletresponse;
    
    /**
    *
    *@作者bert verhelst<verhelst_bert@hotmail.com>
    */
    公共类servlet1扩展了httpservlet{
    
    /**
    *处理对http<code>get</code>和<code>post</code>方法的请求。
    *@参数请求servlet请求
    *@参数响应servlet响应
    *@如果发生servlet特定的错误,则引发servletexception
    *@如果发生I/O错误,则引发IOException
    */
    受保护的void processrequest(httpservletrequest请求,httpservletresponse响应)
    引发ServletException,IOException{
    response.setContentType(“文本/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>正在处理…</h1>”);
    out.println(“</body>”);
    out.println(“</html>”);
    }
    
    //<editor fold defaultstate=“colled”desc=“httpservlet方法。单击左侧的+符号编辑代码。“>
    /**
    *处理http<code>get</code>方法。
    *@参数请求servlet请求
    *@参数响应servlet响应
    *@如果发生servlet特定的错误,则引发servletexception
    *@如果发生I/O错误,则引发IOException
    */
    @重写
    受保护的void doget(httpservletrequest请求,httpservletresponse响应)
    引发ServletException,IOException{
    处理请求(请求、响应);
    printWriter out=response.getWriter();
    out.println(“<!doctype html public\“-//w3c//dtd html 4.0”
    +“过渡//en\”>“\n”
    +“<html>\n”
    +“<head><title>您好,www</title></head>\n”
    +“正文\n”
    +“<h1>狗…</h1>\n”
    +“</body></html>”);
    }
    
    /**
    *处理http<code>post</code>方法。
    *@参数请求servlet请求
    *@参数响应servlet响应
    *@如果发生servlet特定的错误,则引发servletexception
    *@如果发生I/O错误,则引发IOException
    */
    @重写
    受保护的void dopost(httpservletrequest请求,httpservletresponse响应)
    引发ServletException,IOException{
    处理请求(请求、响应);
    printWriter out=response.getWriter();
    out.println(“<!doctype html public\“-//w3c//dtd html 4.0”
    +“过渡//en\”>“\n”
    +“<html>\n”
    +“<head><title>您好,www</title></head>\n”
    +“正文\n”
    +“<h1>doPost…</h1>\n”
    +“</body></html>”);
    }
    
    /**
    *返回servlet的简短描述。
    *@返回包含servlet描述的字符串
    */
    @重写
    公共字符串getServletInfo()。{
    返回“简短描述”;
    }//</editor折叠>
    }
    < /代码> 
    
    

    这是我的Android主页:

    package be.smarttelecom.mytest;
    
    导入android.app.activity;
    导入android.os.bundle;
    导入android.widget.textview;
    
    公共类主扩展活动{
    /**在首次创建活动时调用。*/
    @重写
    public void oncreate(bundle savedinstanceState){
    super.oncreate(保存的状态);
    setContentView(r.layout.main);
    textView输出=(textView)findView byid(r.id.output);
    尝试{
    output.append(“开始\n”);
    restclient client=new restclient(“http://10.0.0.188:8084/servlet_1/servlet1”);
    
    尝试{
    client.execute(requestmethod.get);
    }catch(例外e){
    e.printstacktrace();
    }
    
    output.append(“在执行之后\n”);
    
    字符串响应=client.getResponse();
    output.append(“class-”+response+“\n”);
    output.append(响应);
    output.append(“完成\n”);
    }
    catch(异常ex){
    output.append(“错误:”+ex.getmessage()+“”\n“+ex.toString()+”\n“;”
    }
    }
    }
    < /代码> 
    
    

    最后我们有了restclient:

    package be.smarttelecom.mytest;
    
    导入java.io.bufferedreader;
    导入java.io.ioexception;
    导入java.io.inputstream;
    导入java.io.inputstreamreader;
    导入java.util.arraylist;
    
    导入org.apache.http.httpentity;
    导入org.apache.http.httpresponse;
    导入org.apache.http.namevaluepair;
    导入org.apache.http.client.clientProtocolException;
    导入org.apache.http.client.http client;
    导入org.apache.http.client.entity.urlencodedformentity;
    导入org.apache.http.client.methods.httpget;
    导入org.apache.http.client.methods.httppost;
    导入org.apache.http.client.methods.httpurirequest;
    导入org.apache.http.impl.client.defaulthttpclient;
    导入org.apache.http.message.basicNameValuePair;
    导入org.apache.http.protocol.http;
    
    公共类RestClient{
    private arraylist<名称值对>参数;
    private arraylist<nameValuePair>标题;
    
    私有字符串URL;
    
    私人内部响应代码;
    私有字符串消息;
    
    私有字符串响应;
    
    公共字符串getResponse()。{
    回复;
    }
    
    公共字符串getErrorMessage()。{
    返回消息;
    }
    
    public int getResponseCode()。{
    返回响应代码;
    }
    
    public restclient(字符串URL)
    {
    URL=URL;
    params=new arraylist<名称值对>();
    headers=new arraylist<nameValuePair>();
    }
    
    public void addparam(字符串名称、字符串值)
    {
    params.add(new basicNameValuePair(name,value));
    }
    
    public void addheader(字符串名称、字符串值)
    {
    headers.add(new basicNameValuePair(name,value));
    }
    
    public void execute(requestMethod方法)引发异常
    {
    开关(方法){
    案例获取:
    {
    //添加参数
    字符串CombinedParams=“”;
    如果(!)参数.isEmpty()){
    CombinedParams+=“?”;
    for(名称值对p:params)
    {
    字符串参数string=p.getname()+“=”+p.getvalue();
    if(combinedParams.length()>1)
    {
    CombinedParams+=“&”+ParamString;
    }
    其他的
    {
    CombinedParams+=参数字符串;
    }
    }
    }
    
    httpget请求=new httpget(url+combinedparams);
    
    //添加标题
    for(名称值对h:标题)
    {
    request.addheader(h.getname(),h.getvalue());
    }
    ExecuteRequest(请求,URL);
    断裂;
    }
    
    案例:
    {
    httppost请求=新httppost(url);
    
    //添加标题
    for(名称值对h:标题)
    {
    request.addheader(h.getname(),h.getvalue());
    }
    
    如果(!)参数.isEmpty()){
    request.setentity(新的urlencodedformentity(params,http.utf_8));
    }
    
    ExecuteRequest(请求,URL);
    断裂;
    }
    }
    }
    
    private void executerequest(httpurirequest请求,字符串url)
    {
    httpclient client=new defaulthttpclient();
    
    HTT响应HTT响应;
    
    尝试{
    httpResponse=client.execute(请求);
    responseCode=httpResponse.getStatusLine().getStatusCode();
    message=httpResponse.getStatusLine().getReasonPhrase();
    
    httpEntity实体=httpResponse.getEntity();
    
    如果(实体)!{NULL){
    inputstream instream=entity.getContent();
    响应=ConvertStreamToString(流内);
    
    //关闭输入流将触发连接释放
    instream.close();
    }
    }
    catch(客户端协议例外){
    client.getConnectionManager().shutdown();
    e.printstacktrace();
    }捕获(IOException E){
    client.getConnectionManager().shutdown();
    e.printstacktrace();
    }
    }
    
    私有静态字符串convertstreamToString(inputstream is){
    bufferedreader reader=新bufferedreader(新inputstreamreader(is));
    StringBuilder sb=new StringBuilder();
    
    字符串行=空;
    尝试{
    同时((line=reader.readline())!{NULL){
    附加(行+“\n”);
    }
    }
    捕获(IOException E){
    e.printstacktrace();
    }
    最后{
    尝试{
    是。
    }捕获(IOException E){
    e.printstacktrace();
    }
    }
    返回sb.toString();
    }
    }
    < /代码> 
    
    

    不幸的是,这行不通。这是我为输出(空)所得到的,

    我做错什么了?

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

    我允许在应用程序右括号后的清单文件中进行Internet连接,

    使用权限android:name=“android.permission.internet”/> < /代码> <

    这是我的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();
             }
         }
    

    不幸的是,这行不通。这是我得到的输出值(空),

    Screenshot of

    我做错什么了?

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

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

    <uses-permission android:name="android.permission.INTERNET" />
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Community Lee Campbell    7 年前

    Romain Hippeau 在评论中写道:

    呼叫是否到达servlet?服务器看到什么正在发送?服务器正在发送什么?

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