POST请求中的Android Volley错误。

时间:2016-07-05 16:48:54

标签: android android-studio android-volley androidhttpclient

我的Android代码存在问题。我使用volley lib来发出http个请求。为了登录我的应用程序,我使用下面的代码:

private void checkLogin(final String email_string, final String password_string) {
    String tag_string_req = "req_login";

    pDialog.setMessage("Logging in ...");
    showDialog();

    StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();
            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) {
                    session.setLogin(true);

                    /*
                    String uid = jObj.getString("uid");
                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user.getString("created_at");

                    db.addUser(name, email, uid, created_at);
                    */

                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=utf-8";
        }

        /*
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept-Charset:", "charset=utf-8");
            headers.put("Content-type", "application/x-www-form-urlencoded");
            return headers;
        }
        */

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("email", email_string);
            params.put("password", password_string);
            return params;
        }
    };

    int socketTimeout = 10000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 1, 1);
    strReq.setRetryPolicy(policy);
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

我的登录API是以下代码:

  $app->post('/login', function() use ($app) {
        // check for required params
        verifyRequiredParams(array('email', 'password'));

        // reading post params
        $email = $app->request()->post('email');
        $password = $app->request()->post('password');
        $response = array();


        $db = new DbHandler();
        // check for correct email and password
        if ($db->checkLogin($email, $password)) {
            // get the user by email
            $user = $db->getUserByEmail($email);

            if ($user != NULL) {
                $response["error"] = false;
                $response['name'] = $user['name'];
                $response['email'] = $user['email'];
                $response['apiKey'] = $user['api_key'];
                $response['createdAt'] = $user['created_at'];
            } else {
                // unknown error occurred
                $response['error'] = true;
                $response['message'] = "An error occurred. Please try again";
            }
        } else {
            // user credentials are wrong
            $response['error'] = true;
            $response['message'] = 'Login failed. Incorrect credentials';
        }

        echoRespnse(200, $response);
    });


public function checkLogin($email, $password) {
    // fetching user by email
    $stmt = $this->conn->prepare("SELECT password_hash FROM users WHERE email = ?");

    $stmt->bind_param("s", $email);

    $stmt->execute();

    $stmt->bind_result($password_hash);

    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        // Found user with the email
        // Now verify the password

        $stmt->fetch();

        $stmt->close();

        if (PassHash::check_password($password_hash, $password)) {
            // User password is correct
            return TRUE;
        } else {
            // user password is incorrect
            return FALSE;
        }
    } else {
        $stmt->close();

        // user not existed with the email
        return FALSE;
    }
}

当我尝试使用postman检查我的API,以及POST网址中的参数时,我从API获得了正确的回复。因此,我认为它没有问题。但是,当我尝试使用Android代码时,它总是会返回错误的凭据。我相信我已经添加了正确的参数。我认为问题出在我的标题中。你有什么建议可以解决吗?

0 个答案:

没有答案