-1

I've been trying to send a post request to my XAMPP server to a php file via android studio and I havent been able to get GetOutputStream() to work. Heres my code for android studio:

public class Connect extends AsyncTask<String, Void, String> {
    private Context context;

    public Connect(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... arg0) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        System.setProperty("http.ProxyHost", "some.proxy");
        System.setProperty("http.ProxyPort", "1080");
        try{
            String method = "login";
            //now_method = (String)params[0];
            String data = "";
            if (method.compareTo("register")==0) {

                String username = (String) arg0[0];
                String password = (String) arg0[1];



                //OutputStream out = null;
                String link = "http://localhost:80/project1/";
                data = URLEncoder.encode("method", "UTF-8") + "=" + URLEncoder.encode(method, "UTF-8");
                data += "&" + URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
                data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            }

            String link="http://localhost:80/project1/"; //localhost ip
            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            Log.d("MESSAGE", "got to line 139");
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            Log.d("MESSAGE", "got to line 141");
            wr.write( data );
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            return sb.toString();
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }
}

Heres the code to my php file:

<?php

    function My_register($username, $password)
    {   //connect to database
        $con_db = mysqli_connect("localhost", "root", "", "users_db"); #username: root #password: your Mysql password #database name: your db name

        //check connection
        if (!$con_db) {
            die("Connection failed: " . mysqli_connect_error());
         }
         echo "Connected successfully\n";
         

        //insert user to database table
        $sql_command = "INSERT INTO tb_Users(user_name, pass_word) VALUES('{$username}', '{$password}')";

        if(mysqli_query($con_db, $sql_command)){
            echo "Records inserted successfully.\n";
        } else{
            echo "ERROR: Could not able to execute sql. ";
        }
    
        mysqli_close($con_db);
    }

    function My_login($username, $password){
        $con_db = mysqli_connect("localhost","root", "", "hw1_db");
        if($con_db){
            echo "[DB connection success]---->\n";
        } else{
            echo "DB connection failed\n";
        }
        $sql_command = "SELECT * FROM tb_users WHERE user_name ='$username' AND password='$password'";
        $result = $con_db->query($sql_command);
        if($result->num_rows > 0){
            $row = $result->fetch_assoc();
            $username = $row['user_name'];
            $fullname = $row['full_name'];
            $interest = $row['interest'];
            $result = array('result' => '1', 'username' => $username,'fullname' => $fullname,'interest' => $interest );
            echo json_encode($result);
            #echo 'Succeed;' . $username . ';' . $fullname . ';' . $interest;
        }
        else{
            echo 'Failed';
        }
        $con_db->close();
    }

    $method = "login";
    $username = "";
    $password = "";
    # $method = urldecode($_POST['method']);
    switch ($method) {
        case 'register':
            $username = urldecode($_POST['username']);
            $password = urldecode($_POST['password']);
            My_register($username, $password);
            break;
        case 'login':
            My_login($username, $password);
            $username = urldecode($_POST['username']);
            $password = urldecode($_POST['password']);
            break;
        default:
            echo "[DB connection success]---->\n";
            break;
    }

    ?>

I've tried many different things and nothing has worked, I'm not sure what to do at this point, any advice would be greatly appreciated.Also I do have <uses-permission android:name="android.permission.INTERNET"/> in my androidmanifest.xml

  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Sep 15 '22 at 08:41

1 Answers1

0

Using "http://localhost:80/project1/"; won't work. If you are running app on real device which is connected to same wifi network use your local wifi network IP address instead of localhost like this "http://192.168.xxx.xxx:80/project1/";.

If you are running on emalutor use "http://10.0.2.2:80/project1/";

If you are running on genymotion you can try "http://10.0.3.2:80/project1/";

WS Ayan
  • 451
  • 4
  • 9
  • I am running it on an emulator, I didnt realize how that could be a problem for localhost connections. I tried the http://10.0.2.2:80/project1/ and it didnt work either. Im guessing its the network issue still – Andrew Viera Sep 15 '22 at 16:08