dongxi1943
2015-03-20 16:31
浏览 58

Android认证wampserver

I'm trying to make an android login activity , i made a simple database that contain one table to test my login activity. My problem is that when i even put a right username and password it tells me that the username and password are wrong , i've searched in the forum if someone got a simular problem as mine but i couldn't find one. i'm realy stuck over a month in this problem .. i will appreciate it so much if someone can help me throw this.

This is my Login.java class

public class Login extends Activity implements OnClickListener {
private EditText _myLogin;
private EditText _myPassword;
private String _myContenuLogin;
private String _myContenuPassword;
private boolean _myCheck;
private ProgressDialog _myDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Button lBtnValidate = (Button) findViewById(R.id.authen_btn_valider);
    lBtnValidate.setOnClickListener(this);
    Button lBtnCancel = (Button) findViewById(R.id.authen_btn_annuler);
    lBtnCancel.setOnClickListener(this);

    _myLogin = (EditText) findViewById(R.id.authen_editlogin);
    _myPassword = (EditText) findViewById(R.id.authen_editlmdp);

}


@Override
public void onClick(View v) {

    if (v.getId() == R.id.authen_btn_valider) {
        _myContenuLogin = _myLogin.getText().toString();
        _myContenuPassword = _myPassword.getText().toString();



        MyAsyncTask myTask = new MyAsyncTask();
        myTask.execute(Stat.URL_CHECK);

        if (_myCheck) {
            Toast.makeText(this, "Bienvenue " + _myContenuLogin,
                    Toast.LENGTH_SHORT).show();
            Intent lIntentHome = new Intent(this, Home.class);
            startActivity(lIntentHome);
            this.finish();

        } else {
            Toast.makeText(this,
                    "Nom d'utilisateur ou mot de passe incorrecte",
                    Toast.LENGTH_LONG).show();

        }

    } else if(v.getId() == R.id.authen_btn_annuler){
        this.finish();
    }


}






private class MyAsyncTask extends AsyncTask<String, Void, Boolean>{

    @Override
    protected void onPreExecute() {
        _myDialog = ProgressDialog.show(Login.this, "Vérification", "Attendez SVP...");


    }

    @Override
    //String...params : Array of Strings , on a mis params[0] puisqu'on a une seule chaîne
    protected Boolean doInBackground(String... params) {

        ClientHTTP lClientHTTP=new ClientHTTP(Login.this);

        ArrayList<NameValuePair> list=new ArrayList<NameValuePair>();

        BasicNameValuePair lParamName=new BasicNameValuePair("PARAM_NAME", _myContenuLogin);
        list.add(lParamName);

        BasicNameValuePair lParamPassword=new BasicNameValuePair("PARAM_PASSWORD", _myContenuPassword);
        list.add(lParamPassword);

        _myCheck=lClientHTTP.SendToUrl(params[0], list);

        return _myCheck;
    }
    @Override
    protected void onPostExecute(Boolean result) {
        _myDialog.dismiss();
    }

}

}

This is my Stat.java class that contains useful strings

public class Stat {
public static final String DB_NAME = "leoni.db";
public static final String TABLE_NAME = "agent_sos";
public static final String COL_ID = "id";
public static final String COL_NOM_PRENOM = "nom_prenom";
public static final String COL_MDP = "mot_de_passe";
public static final String URL_CHECK = "http://127.0.0.1/check.php";

}

This is my ClientHTTP.java class wich contains methods to connect , get and send to url

public class ClientHTTP {

private Context _mContext;

public ClientHTTP(Context pContext){
    _mContext=pContext;
}
//méthode pour lire le contenu d'un URL
public String readFromUrl(String strURL) {
    URL clientURL = null;
    HttpURLConnection client = null;
    // Créer un buffer , StringBuilder() permet de créer une chaîne de caractères modifiable
    StringBuilder builder = new StringBuilder();
    // Créer un client Http
    try {
        clientURL = new URL(strURL);
        client = (HttpURLConnection) clientURL.openConnection();
    } catch (MalformedURLException e1) {

        e1.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    // Créer un obejet httpget pour utiliser la methode get
    HttpGet httpGet = new HttpGet(strURL);
    try {
        // récuperer la réponse
        HttpResponse response = ((HttpClient) client).execute(httpGet);
        //
        StatusLine statusLine = response.getStatusLine();
        // récuperer le ack
        int statusCode = statusLine.getStatusCode();
        // si ack =200 connexion avec succée
        if (statusCode == 200) {
            //récuperer l'entité
            HttpEntity entity = response.getEntity();
            //récuperer le contenu de l'entité , 
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            // errur du chargement
            Toast.makeText(_mContext, "pas de connexion", Toast.LENGTH_LONG).show();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}

public boolean SendToUrl(String strURL,ArrayList<NameValuePair> nameValuePairs) {
    // Créer un buffer
    StringBuilder builder = new StringBuilder();
    // Créer un client Http
    HttpClient client = new DefaultHttpClient();
    // Créer un obejet httppost pour utiliser la methode post
    HttpPost httppost = new HttpPost(strURL);
    try {
        //UrlEncodedFormEntit() : An entity composed of a list of url-encoded pairs
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // récuperer la réponse
        HttpResponse response = client.execute(httppost);

        StatusLine statusLine = response.getStatusLine();
        // récuperer le ack
        int statusCode = statusLine.getStatusCode();
        // si ack =200 connexion avec succée
        if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            // erreur du chargement
            Toast.makeText(_mContext, "pas de connexion", Toast.LENGTH_LONG).show();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Boolean.parseBoolean(builder.toString());
}
}

And finaly this is my check.php file

<?php
/*mysql_real_escape_string Protège une commande SQL de la présence des caractères spéciaux */
$username = mysql_real_escape_string($_REQUEST['PARAM_NAME']);
$password = mysql_real_escape_string($_REQUEST['PARAM_PASSWORD']);

  mysql_connect("localhost","root","");
  mysql_select_db("leoni");

$result=mysql_query("SELECT nom_prenom,mot_de_passe FROM agent_sos WHERE nom_prenom ='$username' AND mot_de_passe='$password'");
if (mysql_num_rows($result) == 0) {
   echo "false"; 
} else {
   echo "true";
}

?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujianmin6527 2015-03-27 00:42
    已采纳

    My problem was that i'm using an old version of mysql with wampsever 2.5 so it was a compatibility problem , i fixed it with changing my php script with this :

    <?php
    $mysqli = new mysqli("localhost", "root", "", "leoni");
    
    /* Vérification de la connexion */
    if (mysqli_connect_errno()) {
        printf("Échec de la connexion : %s
    ", mysqli_connect_error());
        exit();
    }
    /* Recuperer les params passées */
    $username = $mysqli->real_escape_string($_POST['PARAM_NAME']);
    $password = $mysqli->real_escape_string($_POST['PARAM_PASSWORD']);
    
    
     $result =  $mysqli->query("SELECT COUNT(*) FROM agent_sos WHERE nom_prenom ='$username' AND mot_de_passe='$password'");
     $row = $result->fetch_row();
     if($row[0] !=0) {
        printf("true");
    }else
        printf("false");
    
    /* Fermeture de la connexion */
    $mysqli->close();
    ?>
    

    and i changed the URL_CHECK with this : 192.168.1.4 which is the result of the command ipconfig my new issue is that it runs perfectly on the emulator but it dosen't work on the device ! why is that ?

    点赞 打赏 评论
  • dshgdhdfcas30210 2015-03-20 17:01

    change this :

     public class Stat {
      public static final String DB_NAME = "leoni.db";
      public static final String TABLE_NAME = "agent_sos";
      public static final String COL_ID = "id";
      public static final String COL_NOM_PRENOM = "nom_prenom";
      public static final String COL_MDP = "mot_de_passe";
      public static final String URL_CHECK = "http://127.0.0.1/check.php";
     }
    

    With this :

     public class Stat {
      public static final String DB_NAME = "leoni.db";
      public static final String TABLE_NAME = "agent_sos";
      public static final String COL_ID = "id";
      public static final String COL_NOM_PRENOM = "nom_prenom";
      public static final String COL_MDP = "mot_de_passe";
      public static final String URL_CHECK = "http://10.0.2.2/check.php"; //If you are using Emulator or your Computer Ip address by using cmd > ipconfig
    
     }
    
    点赞 打赏 评论

相关推荐 更多相似问题