Проблема с подключением и безопасностью вещи Android, MySQL, PHP - PullRequest
0 голосов
/ 21 января 2019

Итак, я пытаюсь войти в свое приложение для Android, используя данные из моей базы данных mysql, и Android Studio вернула мне эти сообщения в терминале. Ниже приведен код, который я использую в Android Studio, и сообщения терминала. Я написал IP-адрес и порт с "**" из соображений безопасности.

Кто-то может помочь мне понять, что происходит?

LoginActivity.java

package com.pedido.meu.telas_meu_pedido.controller;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.pedido.meu.telas_meu_pedido.R;
import com.pedido.meu.telas_meu_pedido.modelo.AssyncLogin;

public class LoginActivity extends AppCompatActivity
{
    private EditText editTextUsername, editTextPassword;
    private Button btnLogin;

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

        editTextUsername = findViewById(R.id.txtLogin);
        editTextPassword = findViewById(R.id.txtPassword);
        btnLogin = findViewById(R.id.btnLogin);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username = editTextUsername.getText().toString().trim();
                final String password = editTextPassword.getText().toString().trim();

                new AssyncLogin(LoginActivity.this).execute(username, password);
            }
        });
    }

}

AssyncLogin.java

package com.pedido.meu.telas_meu_pedido.modelo;

import com.pedido.meu.telas_meu_pedido.controller.ListaProdutosActivity;
import com.pedido.meu.telas_meu_pedido.controller.LoginActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class AssyncLogin extends AsyncTask<String, String, String>
{
    private LoginActivity loginActivity;
 //   ProgressBar progressBarLoading = new ProgressBar(loginActivity);
    HttpURLConnection conn;
    URL url = null;

    public AssyncLogin(LoginActivity loginActivity) {
        this.loginActivity = loginActivity;
    }

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

        //this method will be running on UI thread
     //   progressBarLoading.draw();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            url = new URL("http://192.168.15.12/magnero/login.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("username", params[0])
                    .appendQueryParameter("password", params[1]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

    //    pdLoading.dismiss();

        if (result.equalsIgnoreCase("true")) {
            Intent intent = new Intent(loginActivity, ListaProdutosActivity.class);
            loginActivity.startActivity(intent);
            loginActivity.finish();

        } else if (result.equalsIgnoreCase("false")) {

            // If username and password does not match display a error message
            Toast.makeText(loginActivity, "Invalid userename or password", Toast.LENGTH_LONG);

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast.makeText(loginActivity, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG);

        }
    }    
}

login.php

<?php

    include 'conexao.php';
    $result='';
     if(isset($_POST['username']) && isset($_POST['password']))
     {


          $username = $_POST['username'];
          $password = $_POST['password'];


          $sql = 'SELECT * FROM afiliado WHERE  email = :username AND senha = :password';
          $stmt = $conn->prepare($sql);
          $stmt->bindParam(':email', $username, PDO::PARAM_STR);
          $stmt->bindParam(':senha', $password, PDO::PARAM_STR);
          $stmt->execute();
          if($stmt->rowCount())
          {
          $result="true";   
          }  
          elseif(!$stmt->rowCount())
          {
            $result="false";
          }

            echo $result;
   }

?>

conexao.php

<?php
define('hostname', 'https://auth-db100.hostinger.com.br/index.php');
define('user', 'user');
define('password', 'password');
define('databaseName', 'database_mysql');
$connect = mysqli_connect(hostname, user, password, databaseName);
?>

Сообщения терминала

No Network Security Config specified, using platform default
W/System.err: java.net.SocketTimeoutException: failed to connect to /******* (port ***) from /********** (port ****) after 10000ms
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:185)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:129)
        at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
        at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:26)
W/System.err:     at com.pedido.meu.telas_meu_pedido.modelo.AssyncLogin.doInBackground(AssyncLogin.java:70)
W/System.err:     at com.pedido.meu.telas_meu_pedido.modelo.AssyncLogin.doInBackground(AssyncLogin.java:21)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:764)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...