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

Posted

技术标签:

【中文标题】如何将数据从 servlet 传递到 android 应用程序【英文标题】:how to pass data from servlet to android application 【发布时间】:2011-06-11 14:46:51 【问题描述】:
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>


这是我的安卓应用程序

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

            
        
    ;

【问题讨论】:

您需要添加更多信息。你是如何提出要求的。 如何在request中添加以及如何在android应用中处理 你能补充一些信息吗?您在寻求什么样的帮助? 【参考方案1】:

您需要为您的 servlet 页面创建一个 URLConnection 并执行此操作。例如:How to download file/image from url to your device

【讨论】:

【参考方案2】:

您可以通过json format 将数据从servlet 获取到andriod 应用程序。 请通过此http://wiebe-elsinga.com/blog/?p=405 链接了解如何从 Android 应用程序调用 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;
     

// 从服务器获取数据到安卓

   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】:

首先, 如果你的doGet()doPost() 做同样的事情,你可以打电话给另一个,发送requestresponse

其次,您可以将ArrayList&lt;E&gt; 传递给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 streamcatch (MalformedURLException exception) catch (IOException exception)

【讨论】:

但是如何给android url??我怎样才能找到它【参考方案4】:

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

Send arraylist from servlet to Android application

【讨论】:

以上是关于如何将数据从 servlet 传递到 android 应用程序的主要内容,如果未能解决你的问题,请参考以下文章

如何将错误从服务层传递到 vanilla Java Servlet? [复制]

使用 java servlet 将数据从一个 html 页面传递到另一个页面

使用 Serializable - AndroidX 将数据从 RecyclerView 传递到 RecyclerViewMore

ExtJs 3.4:从网格中获取所有记录并将它们传递到 servlet

纯 Javascript fetch() 方法到 java Servlet,我如何获取和传递数据?

将数组与 bean 一起从 servlet 传递到 jsp