HttpUrlConnection - Use php to connect in Mysql

0

I am trying to fetch the data of a user saved in an external database to log in / register. But I run the system and there is no exception, but it does not connect. I tested the php that I'm consuming and it's working correctly. If anyone can help me, I'll be grateful.

Class that executes the connection / inserts:

public class BackgroundWorker extends AsyncTask<String, Void, String> {

Context context;
AlertDialog alertDialog;
String result="";

BackgroundWorker(Context context){
    this.context = context;
}

@Override
protected void onPreExecute () {
    super.onPreExecute();

}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String register_url = "http://127.0.0.1/Tutorial/cadastrar.php";
    String login_url = "http://127.0.0.1/Tutorial/login.php";
    if (type.equals("login")) {
        try {
            String user = params[1];
            String pass = params[2];

            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(user, "UTF-8") + "&"
                    + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

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

MainActivity:

public class MainActivity extends AppCompatActivity {
EditText edtLogin;
EditText edtPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edtLogin = (EditText) findViewById(R.id.edtLogin);
    edtPass = (EditText) findViewById(R.id.edtPassword);

}

public void onLogin(View view){
    String username = edtLogin.getText().toString();
    String password = edtPass.getText().toString();
    String type = "login";

    BackgroundWorker bkw = new BackgroundWorker(this);
    bkw.execute(type, username, password);

}

public void actCadastrar(View view){
    startActivity(new Intent(MainActivity.this, Cadastrar.class));
}
}

Php Connection and then php login:

<?php
try {
    $conexao = new PDO("mysql:host=127.0.0.1;dbname=escola", 'root', '') ;
    $conexao->exec("set names utf-8") ;
    $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) ;
    echo 'Conectado';
} catch (PDOException $e) {
    echo 'ERRO: ' . $e->getMessage() ;
}
?>

<?php
session_start() ;

$user = $_POST["user"] ;
$pass = $_POST["pass"] ;

try {
    require('conexao.php') ;
    $sql = "SELECT * FROM escola_tabela Where username = :username And password = :password" ;
    $stmt = $conexao->prepare($sql) ;
    $stmt->execute(array('username' => $user, 'password' => $pass)) ;

    $logou = 0 ;

    while($consulta = $stmt->fetch()) {
        $user = $consulta["username"] ;
        $pass = $consulta["password"] ;

        $_SESSION['username'] = $user ;
        $_SESSION['password'] = $pass ;

        $logou = 1 ;

        echo 'Logado com sucesso';
    }

    if ($logou == 0) {
        echo 'Usuário/Senha inválido...: ' ;
    }


} catch (PDOException $e) {
    echo 'ERRO: ' . $e->getMessage() ;
}

?>
    
asked by anonymous 21.09.2016 / 23:37

1 answer

1

Gabriel, if you are running both the emulator VM and the server, 127.0.0.1 will refer to the emulator itself instead of the server. For this case, just change

String register_url = "http://10.0.2.2/Tutorial/cadastrar.php";
String login_url = "http://10.0.2.2/Tutorial/login.php";
The URL with 10.0.2.2 is a loopback interface host, meaning it will point to the VM host, which is 127.0.0.1 you want!

However, if you are not using the emulator, simply use your IPv4 address.

One more note, I believe your post_data variable is not suitable for your PHP file, it receives both the user and pass POST method, and you're sending username and password !

    
22.09.2016 / 04:21