Httpurlconnection - Use php to connect to Mysql

Asked

Viewed 324 times

0

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

Class running connection/insert:

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 logging in:

<?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() ;
}

?>

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 host interface, meaning it will point to the VM host, which is the 127.0.0.1 you want!

However, if you are not using the emulator, just use your Ipv4 address.

One more remark, I believe your variable post_data is not suitable for your PHP file, it gets in the POST method user and pass, and you’re in charge username and password!

  • I believe that the URL is not the error, I Utlizei Ipv4 and it did not work by mobile. But by emulator worked successfully inserting and login. I believe it’s some configuration..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.