2

I have almost tried everything to make a simple login application so that I can login using servlet. But not able to. I am trying to check the credentials from a web server for which I have given connection of: 203.199.134.131:8080/myserver. This is my Servlet:

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AndroidServlet extends HttpServlet {

    private static final long serialVersionUID = 1084936780013849522L;

    /**
     * Constructor of the object.
     */
    public AndroidServlet() {
        super();
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to
     * post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Connection connection = null;
        Statement statment = null;
        ResultSet result;

        String UserId = request.getParameter("id");
        String Password = request.getParameter("password");

        try {
            // Connect to database retrieve user credentials
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://203.199.134.131:8080/myserver", "fleetview", "1@flv");
            statment = connection.createStatement();
            result = statment
                    .executeQuery("SELECT password FROM db_gps.t_security WHERE username='"
                            + UserId + "';");
            result.next();
            if (result.getObject("password").toString().compareTo(Password) == 0) {

                response.setContentType("text/html");
                ObjectOutputStream oos = new ObjectOutputStream(response
                        .getOutputStream());
                oos.writeObject("Success");
                oos.flush();
                oos.close();
            } else {
                response.setContentType("text/html");
                ObjectOutputStream oos = new ObjectOutputStream(response
                        .getOutputStream());
                oos.writeObject("incorrect");
                oos.flush();
                oos.close();
            }
        } catch (SQLException e) {
            response.setContentType("text/html");
            ObjectOutputStream oos = new ObjectOutputStream(response
                    .getOutputStream());
            oos.writeObject("incorrect");
            oos.flush();
            oos.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statment != null) {
                    statment.close();
                    statment = null;
                }
                if (connection != null) {
                    connection.close();
                    connection = null;
                }
            } catch (SQLException e) {
            }
        }

    }

}

This is my android class:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Connector extends Activity implements OnClickListener{
    EditText Id, Password;
    Button submit;
    AlertDialog alertDialog;
    Activity activity;
    HttpPost httppost = new HttpPost();
    HttpClient httpclient = new DefaultHttpClient();
    String username;
    String password,responseText;

    public static final String URL = "http://192.168.56.1:8080/server/AndroidServlet";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewsById();

        submit.setOnClickListener(this);
    }
    private void findViewsById() {

        Id = (EditText) findViewById(R.id.Id);
        Password = (EditText) findViewById(R.id.Password);
        submit = (Button) findViewById(R.id.submit);
    }
        public void onClick(View view) {
           LoginListener task = new LoginListener();
            task.execute(new String[] { URL });

    }


    class LoginListener extends AsyncTask<String, Void, String> { 


            //send info to server
        protected void preExecute() {
                String username = Id.getText().toString();
                String password = Password.getText().toString();
                 httppost = new HttpPost("http://192.168.56.1:8080/server/AndroidServlet");

                List<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>(2);
                namevaluepairs.add(new BasicNameValuePair("id",username));
                namevaluepairs.add(new BasicNameValuePair("password",password));
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
// // Execute HTTP Post Request
        protected String doInBackground(String... params) {
                    String output = null;
                    try{ 
                httppost = new HttpPost("http://192.168.56.1:8080/server/AndroidServlet");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity rp = response.getEntity();
                String origresponseText =  EntityUtils.toString(rp);

                String responseText = origresponseText.substring(7, origresponseText.length());
                if(responseText.equals("incorrect"))
                {
                    AlertDialog.Builder alt_bld = new AlertDialog.Builder(activity);
                    alt_bld.setMessage("Please Enter Valid credentials")
                    .setCancelable(false)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    // Action for 'Yes' Button
                    }
                    });
                    AlertDialog alert = alt_bld.create();
                    // Title for AlertDialog
                    alert.setTitle("Title");
                    // Icon for AlertDialog
                    alert.setIcon(R.drawable.icon);
                    alert.show();
                }
                    }
                catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParseException e) {
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return output;
            }

                   // }else {
                    protected void onPostExecute() {


                        Intent intent = new Intent(activity,Success.class);
                        intent.putExtra("username",username);
                        intent.putExtra("rp", responseText);

                        startActivity(intent);
                    }


    }

} Log cat Output:

07-16 12:30:29.700: W/System.err(1096): org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.56.1:8080 refused
07-16 12:30:29.728: W/System.err(1096):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
07-16 12:30:29.796: W/System.err(1096):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-16 12:30:29.840: W/System.err(1096):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-16 12:30:29.840: W/System.err(1096):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-16 12:30:29.840: W/System.err(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-16 12:30:29.852: W/System.err(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-16 12:30:29.852: W/System.err(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-16 12:30:29.852: W/System.err(1096):     at com.example.simplehttpgetservlet.Connector$LoginListener.doInBackground(Connector.java:88)
07-16 12:30:29.852: W/System.err(1096):     at com.example.simplehttpgetservlet.Connector$LoginListener.doInBackground(Connector.java:1)
07-16 12:30:29.852: W/System.err(1096):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-16 12:30:29.852: W/System.err(1096):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-16 12:30:29.852: W/System.err(1096):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-16 12:30:30.040: W/System.err(1096):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-16 12:30:30.040: W/System.err(1096):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-16 12:30:30.044: W/System.err(1096):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-16 12:30:30.044: W/System.err(1096):     at java.lang.Thread.run(Thread.java:856)
07-16 12:30:30.044: W/System.err(1096): Caused by: java.net.ConnectException: failed to connect to /192.168.56.1 (port 8080): connect failed: ECONNREFUSED (Connection refused)
07-16 12:30:30.076: W/System.err(1096):     at libcore.io.IoBridge.connect(IoBridge.java:114)
07-16 12:30:30.076: W/System.err(1096):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-16 12:30:30.096: W/System.err(1096):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-16 12:30:30.096: W/System.err(1096):     at java.net.Socket.connect(Socket.java:842)
07-16 12:30:30.116: W/System.err(1096):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-16 12:30:30.116: W/System.err(1096):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-16 12:30:30.116: W/System.err(1096):     ... 15 more
07-16 12:30:30.116: W/System.err(1096): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
07-16 12:30:30.116: W/System.err(1096):     at libcore.io.Posix.connect(Native Method)
07-16 12:30:30.116: W/System.err(1096):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
07-16 12:30:30.116: W/System.err(1096):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-16 12:30:30.116: W/System.err(1096):     at libcore.io.IoBridge.connect(IoBridge.java:112)
07-16 12:30:30.116: W/System.err(1096):     ... 20 more
Adi
  • 111
  • 1
  • 11

2 Answers2

0

add the following permissions in the android manifest file just above the application tag

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
nobalG
  • 4,798
  • 3
  • 29
  • 63
0

I have found the answer of this and since when I was making the application that was a starting thing for me so my code is jumbled too. So I am posting both the part i.e servlet and android clearly. Hope it will help someone to understand the working perfectly....

This is code for servlet:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import connection.MySqlConnection;

public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Objects used...............



        Connection con;     
        String uname=null;
        String pwd=null;
        Statement st=null;
        PrintWriter pw=response.getWriter();
        String query;
        ResultSet rs;
        ResultSetMetaData rsmd;
        int columncount=0;
        PreparedStatement pst=null; 
        System.out.println("in the servlet");
        Enumeration en;
        String temp;

        en=request.getParameterNames();

        while(en.hasMoreElements())
        {
            temp=en.nextElement().toString();
        System.out.println(temp+"-->"+request.getParameter(temp));
        }


    // This is used because my one servlet class is interacting with more than one activity and for each activity i have different connection:  
        if(request.getParameter("username")!=null&&request.getParameter("password")!=null)
        {
             uname=request.getParameter("username");
             pwd=request.getParameter("password");

            System.out.println(uname+""+pwd);
            try
            {
                con=connection.MySqlConnection.getLoginConnection();

                st=con.createStatement();
                //String query="select * from demo";
                 query= "SELECT username,password, ActiveStatus FROM twsql_twalldata.t_security  where username= '"+uname+"' and password='"+pwd+"'";
                rs=st.executeQuery(query);


                if(rs.next()) 
                {
                    if(rs.getString(1).equals(uname)&&rs.getString(2).equals(pwd)&& rs.getString(3).equalsIgnoreCase("yes"))
                    { 

                        pw.println("login Successful");

                    }

                }
                else
                {
                    pw.println("login failed. Please check your credentials.");                     
                }

                con.close();

            }
            catch(Exception e)

            {
                e.printStackTrace();
                System.out.println("connection failure...!");
                pw.println("connection failure...!");
            }

        }// login-if-condition
 }//doGet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

Now this is the Mysqlconnection class in connection package:

package connection;

import java.sql.Connection;
import java.sql.DriverManager;

public class MySqlConnection {

    public static Connection con=null;


    static
    {
        try
        {
        Class.forName("org.gjt.mm.mysql.Driver");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

    public static Connection getLoginConnection()
    {   

        try
        {           
            con=DriverManager.getConnection("jdbc:mysql://203.199.134.131/twsql_twalldata", "erp", "1@erp");
        }//try
        catch(Exception e)
        {
            e.printStackTrace();            
        }//catch                
        return con; 
    }//getConnection

Now when we run the servlet the url which we get in the adrress bar same should be used in the android accept the ip address which is different for different devices: in genymotion : 192.168.56.1 for default avd: 10.0.2.2 for debugging on physical device : ipv4 addr(if ur servlet is in the machine) Servere ip (if the servlet is deployed on the server)

Now this is the android code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

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 android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Connector extends Activity implements OnClickListener{
    EditText Id, Password;
    Button submit;
   Connector activity;
    HttpPost httppost = new HttpPost();
    String username, password, s1,s2;
 private ProgressBar pb;
    Context c;

 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

     findViewsById();

        submit.setOnClickListener(this);
    }
    private void findViewsById() {

        Id = (EditText) findViewById(R.id.Id);
        Password = (EditText) findViewById(R.id.Password);
        submit = (Button) findViewById(R.id.submit);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);
      c=this;
    }
        public void onClick(View view) {
            s1 = Id.getText().toString();
            s2   = Password.getText().toString();
          pb.setVisibility(View.VISIBLE);  
            if(s1.matches("")||s2.matches("")){
                Toast.makeText(c, "Credentials are Blank", Toast.LENGTH_LONG).show();
         pb.setVisibility(View.INVISIBLE);
            }
else{
new MyAsyncTask().execute(s1,s2);

                }

// ASync task starting

private class MyAsyncTask extends AsyncTask<String, Integer, String>{


        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            String s=postData(params);

            return s;
        }

            protected void onPostExecute(String result){
            //Log.d("on post ","on post execute");
            pb.setVisibility(View.GONE);

 if(result.contains("Successful")){
            Toast.makeText(getApplicationContext(),"Logged in Susccessful", Toast.LENGTH_LONG).show();
            Intent intent_name = new Intent();
            intent_name.setClass(getApplicationContext(),GetAppointment.class);
            intent_name.putExtra("repname", s1);
            startActivity(intent_name);

        }
            else if(result.contains("failed")){
                Toast.makeText(getApplicationContext(),"Login Unsuccesful.Please check your credentials and try again", Toast.LENGTH_LONG).show();
                    }
            else if(result.contains("failure")){

                    Toast.makeText(getApplicationContext(),"Your Internet Connection is Poor.Please try again later", Toast.LENGTH_LONG).show();

            }
        }

        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }


        public String postData(String valueIWantToSend[]) {

             String origresponseText="";
            try {
                // Add your data...............
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("username",valueIWantToSend[0]));

                nameValuePairs.add(new BasicNameValuePair("password", valueIWantToSend[1]));

                HttpClient httpclient = new DefaultHttpClient();

                //httppost = new HttpPost("http://192.168.56.1:8080/ERPServlet/MyServlet");
                 httppost = new HttpPost("http://203.199.134.131:8080/ERPServlet/MyServlet");

                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);

origresponseText=readContent(response);

httpclient.getConnectionManager().shutdown();
System.out.println("Connection close");

            } 

      catch (IOException e) {
                // TODO Auto-generated catch block
            }

          return responseText;



        }



    String readContent(HttpResponse response)
    {

        String text = "";
        InputStream in =null;


        try {
            in = response.getEntity().getContent();


            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
             InputStreamReader(instream, "UTF-8"), 8000);


                }
            in.close();
                text = sb.toString();

        } 
        catch (IllegalStateException e) {
            e.printStackTrace();

        } catch (IOException e) {
              e.printStackTrace();
        }
        finally {
            try {
                if (in != null) {
              in.close();
            }
            }catch (Exception ex) {
            }
            }


return text;







}
    }

}

I hope i have clearly mentioned everything . Atlast do not forget to add the necessary pemission as here only one for the Internet is needed. Thanks

Adi
  • 111
  • 1
  • 11