首页 > 解决方案 > 在 Android 上通过 HttpURLConnection 处理 php 回显数据

问题描述

我正在尝试通过此活动在 android 应用上登录用户:

    public class LoginActivity extends AppCompatActivity implements View.OnKeyListener{


        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View v ) {
                userLogin();
            }
        });


    }


    private void userLogin() {
        String userName = edtUsername.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();

        String method = "login";

        BackgroundTask backgroundTask = new BackgroundTask(this);
        backgroundTask.execute(method,userName,password);


        startActivity(new Intent(getApplicationContext(),MainMenuActivity.class));
        finish();
    }

}

使用此背景任务:

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

    Context ctx;
    HttpURLConnection conn;

    BackgroundTask(Context ctx) {
        this.ctx = ctx;
    }

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

        String method = params[0];
        if (method.equals("register")) {
            String firstName = params[1];
            String lastName = params[2];
            String userName = params[3];
            String email = params[4];
            String pass = params[5];

            Log.i("inBackgground", firstName + " " + lastName + " " + userName + " " + email);

            try {
                URL url = new URL(URLs.URL_REGISTER);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);

                OutputStream os = httpURLConnection.getOutputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                String data = URLEncoder.encode("first", "UTF-8") + "=" + URLEncoder.encode(firstName, "UTF-8") + "&" +
                        URLEncoder.encode("last", "UTF-8") + "=" + URLEncoder.encode(lastName, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                        URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8") + "&" +
                        URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");

                Log.i("inbackgroundFURTHER", data);


                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                os.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                inputStream.close();


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            }

        }


        if (method.equals("login")) {
            String jsonString;

            String userName = params[1];
            String password = params[2];

            try {
                URL url = new URL(URLs.URL_LOGIN);
                conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                OutputStream os = conn.getOutputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                String data = URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8") + "&" +
                        URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&";


                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                os.close();
                conn.connect();



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.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
                    Log.i("resultobj: ", result.toString());
                    return(result.toString());


                }else{
                    Log.i("response code: ", Integer.toString(response_code));
                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }
        }
        return "i don't know what to return here";
    }


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

    @Override
    protected void onPostExecute( String result ) {

        Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onProgressUpdate( Void... values ) {
        super.onProgressUpdate(values);
    }
}

使用的 php 脚本如下所示:

<?php
include 'dbh.inc.php';

$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

$response = array();

$sql = "SELECT * FROM users WHERE user_uid='$uid' OR user_email='$uid';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
    exit();
} else {
    if ($row = mysqli_fetch_assoc($result)) {
        //De-hashing the password
        $hashedPwdCheck = password_verify($pwd, $row['user_pwd']);
        if ($hashedPwdCheck == false) {
            exit();
        } elseif ($hashedPwdCheck == true) {

            $user = array();
            $user["user_id"] = $row[0];
            $user["user_first"] = $row[1];
            $user["user_last"] = $row[2];
            $user["user_email"] = $row[3];
            $user["user_uid"] = $row[4];

            $response["success"] = 1;
            $response["user"] = array();

            array_push($response["user"], $user)

            echo json_encode($response);
            exit();
        }
        exit();


    }
}

目前,我试图在使用 sharedprefs 和用户对象进入下一步之前显示结果,以保持用户登录并使用其用户信息执行某些操作。

问题是,我没有得到任何 HTTP 错误代码 500 的结果。

我究竟做错了什么?

如果我需要提供更多信息,请告诉我!

标签: javaphpandroidhttp

解决方案


PHP 脚本中的问题,尝试用此代码替换它以处理错误。

  <?php
    include 'dbh.inc.php';

    $uid = mysqli_real_escape_string($conn, $_POST['uid']);
    $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

    $response = array();

    $sql = "SELECT * FROM users WHERE user_uid='$uid' OR user_email='$uid';";
    $result = mysqli_query($conn, $sql);
    $resultCheck = mysqli_num_rows($result);
    if ($resultCheck < 1) {
        echo 'error resultCheck < 1';
        exit();
    } else {
        if ($row = mysqli_fetch_assoc($result)) {
            //De-hashing the password
            $hashedPwdCheck = password_verify($pwd, $row['user_pwd']);
            if ($hashedPwdCheck == false) {
             echo 'error hashedPwdCheck == false';
             exit();
            } elseif ($hashedPwdCheck == true) {

                $user = array();
                $user["user_id"] = $row[0];
                $user["user_first"] = $row[1];
                $user["user_last"] = $row[2];
                $user["user_email"] = $row[3];
                $user["user_uid"] = $row[4];

                $response["success"] = 1;
                $response["user"] = array();

                array_push($response["user"], $user)

                echo json_encode($response);
                exit();
            }
           echo 'final exit';
           exit();


        }
    }

推荐阅读