如何将数据从servlet传递到android应用程序

时间:2011-01-19 08:32:46

标签: java android servlets

I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;



/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * 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
 */

        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet form</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet form at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */




@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
} 

/** 
 * 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 {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

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

}

这是我的Android应用程序

package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

            String result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            nameValuePairs.add(new BasicNameValuePair("email", email));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }


            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

            }
        }
    };
}

4 个答案:

答案 0 :(得分:2)

您需要对servlet页面进行URLConnection并执行此操作。示例:How to download file/image from url to your device

答案 1 :(得分:0)

首先, 如果您的doGet()doPost()执行相同的操作,则可以从另一方拨打电话,发送requestresponse

其次,您可以将ArrayList<E>传递给Android应用。 Servlet和Android API都有它

编辑: 您需要从HttpURLConnection对象生成的InputStream中读取。 http://developer.android.com/reference/java/io/InputStream.html

看看这本书: 旧书http://www.amazon.com/Professional-Android-Application-Development-Programmer/dp/0470565527

String input = getString(R.string.input);
try {
    URL url = new URL(input);
    URLConnection connection = url.openConnection();
    HttpURLConnection http = (HttpURLConnection)connection;
    int response = http.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
        InputStream is = http.getInputStream();
        //do whatever you want with the stream
    }
}
catch (MalformedURLException exception) { }
catch (IOException exception) { }

答案 2 :(得分:0)

您可以通过json format从servlet获取数据到andriod应用程序。 请仔细阅读     http://wiebe-elsinga.com/blog/?p=405链接以了解如何从andriod应用程序调用Servlet并获取响应 回到json格式。

从Andriod调用Servlet

  private InputStream callService(String text) {
          InputStream in = null;
           SERVLET_URL = http://wizkid.com/web/updateServlet";
          try {
               URL url = new URL(SERVLET_URL);
               URLConnection conn = url.openConnection();

               HttpURLConnection httpConn = (HttpURLConnection) conn;
               httpConn.setRequestMethod("POST");
               httpConn.setDoInput(true);
               httpConn.setDoOutput(true);
               httpConn.connect();

               DataOutputStream dataStream = new DataOutputStream(conn
                         .getOutputStream());

               dataStream.writeBytes(text);
               dataStream.flush();
               dataStream.close();

               int responseCode = httpConn.getResponseCode();
               if (responseCode == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
               }
          } catch (Exception ex) {
               display("Error: Not not connect");
          }
          return in;
     }

//从服务器获取数据到andriod

   private String getResultFromServlet(String text) {
          String result = "";

          InputStream in = callService(text);
          if (in != null) {
               JSONObject jsonResponse;
               try {
                    jsonResponse = new JSONObject(convertStreamToString(in));
                    result = jsonResponse.getString("output");
               } catch (JSONException e) {
                    result = "Error: JSON Object couldn't be made";
               }
          } else {
               result = "Error: Service not returning result";
          }
          return result;
     }

答案 3 :(得分:0)

你可以在这里查看。有一个包含示例代码的完整描述

Send arraylist from servlet to Android application