代码之家  ›  专栏  ›  技术社区  ›  Ingor Sievaz

在Android上通过HttpURLConnection处理php echo数据

  •  0
  • Ingor Sievaz  · 技术社区  · 6 年前

    我正在尝试通过以下活动登录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
    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和user对象进入下一步之前显示一个结果,以便保持用户登录并对其用户信息进行处理。

    我做错什么了?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Momen Zaqout    6 年前

    对于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();
    
    
            }
        }
    
        2
  •  0
  •   Ingor Sievaz    6 年前

    我改变了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)) {
            $row = mysqli_fetch_array($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($user);
                exit();
            }
           echo 'final exit';
           exit();
    
    
        }
    }