как передать данные из сервлета в приложение для Android - PullRequest
4 голосов
/ 19 января 2011
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 ]

2 голосов
/ 19 января 2011

Вам нужно сделать URLConnection со своей страницей сервлета и сделать это.Пример для этого: Как загрузить файл / изображение с URL на ваше устройство

0 голосов
/ 03 января 2013

Вы можете проверить здесь. Есть полное описание с примером кода

Отправка архива из сервлета в приложение Android

0 голосов
/ 19 января 2011

вы можете получить данные из сервлета в приложение andriod через json format.Перейдите по этой
http://wiebe -elsinga.com / blog /? P = 405 ссылке, чтобы понять, как вызвать сервлет из приложения andriod и получить ответ обратно в формате json.

вызов сервлета от Andriod

  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;
     }
0 голосов
/ 19 января 2011

Прежде всего, если ваши doGet() и doPost() делают одно и то же, вы можете позвонить одному из другого, отправив request и response

Во-вторых, вы можете передатьArrayList<E> в приложение для Android.API-интерфейс сервлетов и Android имеют

edit: вам нужно читать из InputStream, сгенерированного объектом HttpURLConnection.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) { }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...