获取json错误:输入结束于0的字符

时间:2016-03-01 08:57:45

标签: java php android mysql json

PHP文件:

<?php


require_once('include/db_functions.php');
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['email']) && isset($_POST['password'])) {

    // receiving the post params
    $email = $_POST['email'];
    $password = $_POST['password'];

    // get the user by email and password
    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {
        // use is found
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];

    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
}
echo json_encode($response);
?>

Java代码:

private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

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

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

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();

            try {

                int jsonStart = response.indexOf('{');
                int jsonEnd = response.lastIndexOf('}');
                if(jsonStart>=0 && jsonEnd>=0 && jsonEnd>jsonStart) response = response.substring(jsonStart,jsonEnd+1);
                else response = "";
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {
                    // user successfully logged in
                    // Create login session
                    session.setLogin(true);

                    // Now store the user in SQLite
                    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");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                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
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
  

更新1:   logcat的:

03-01 15:13:12.889 2099-2099/challenge.edison.harvest I/art: Not late-

enabling -Xcheck:jni (already on)
03-01 15:13:13.021 2099-2099/challenge.edison.harvest W/System: ClassLoader referenced unknown path: /data/app/challenge.edison.harvest-1/lib/x86
03-01 15:13:13.143 2099-2113/challenge.edison.harvest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-01 15:13:13.256 2099-2113/challenge.edison.harvest I/OpenGLRenderer: Initialized EGL, version 1.4
03-01 15:13:13.386 2099-2113/challenge.edison.harvest W/EGL_emulation: eglSurfaceAttrib not implemented
03-01 15:13:13.386 2099-2113/challenge.edison.harvest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7345a0, error=EGL_SUCCESS
03-01 15:13:30.769 2099-2113/challenge.edison.harvest W/EGL_emulation: eglSurfaceAttrib not implemented
03-01 15:13:30.769 2099-2113/challenge.edison.harvest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad73a840, error=EGL_SUCCESS
03-01 15:13:33.005 2099-2105/challenge.edison.harvest W/art: Suspending all threads took: 779.254ms
03-01 15:13:33.006 2099-2099/challenge.edison.harvest I/Choreographer: Skipped 48 frames!  The application may be doing too much work on its main thread.
03-01 15:13:34.301 2099-2105/challenge.edison.harvest W/art: Suspending all threads took: 629.777ms
03-01 15:13:34.302 2099-2099/challenge.edison.harvest I/Choreographer: Skipped 38 frames!  The application may be doing too much work on its main thread.
03-01 15:13:35.046 2099-2099/challenge.edison.harvest D/RegisterActivity: Login Response: <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'><b>PHP Error Message</b></font></td></tr></table><br />
                                                                          <b>Fatal error</b>:  Call to undefined method mysqli_stmt::get_result() in <b>/home/a6777446/public_html/include/db_functions.php</b> on line <b>64</b><br />
                                                                          <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'><a href='http://www.000webhost.com/'><font face='Arial' size='1' color='#000000'>Free Web Hosting</font></a></div></td></tr></table>
03-01 15:13:35.089 2099-2113/challenge.edison.harvest E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7510d0
03-01 15:13:35.096 2099-2099/challenge.edison.harvest W/System.err: org.json.JSONException: End of input at character 0 of 
03-01 15:13:35.096 2099-2099/challenge.edison.harvest W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err:     at challenge.edison.harvest.LoginActivity$3.onResponse(LoginActivity.java:128)
03-01 15:13:35.100 2099-2099/challenge.edison.harvest W/System.err:     at challenge.edison.harvest.LoginActivity$3.onResponse(LoginActivity.java:115)
03-01 15:13:35.102 2099-2099/challenge.edison.harvest W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-01 15:13:35.103 2099-2099/challenge.edison.harvest W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-01 15:13:35.103 2099-2099/challenge.edison.harvest W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-01 15:13:35.103 2099-2099/challenge.edison.harvest W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-01 15:13:35.113 2099-2099/challenge.edison.harvest D/Volley: [1] Request.finish: 4449 ms: [ ] http://edisonharvest.comxa.com/login.php 0xafab10d0 NORMAL 1
03-01 15:13:35.242 2099-2113/challenge.edison.harvest W/EGL_emulation: eglSurfaceAttrib not implemented
03-01 15:13:35.242 2099-2113/challenge.edison.harvest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad75aae0, error=EGL_SUCCESS
03-01 15:13:38.626 2099-2113/challenge.edison.harvest E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7524f0
  

更新2:   DB_FUNCTIONS.php

<?php

class DB_Functions {

    private $conn;

    // constructor
    function __construct() {
        require_once 'db_connect.php';
        // connecting to database
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt

        $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
        $result = $stmt->execute();
        $stmt->close();

        // check for successful store
        if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            return $user;
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {

        $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");

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

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            // verifying user password
            $salt = $user['salt'];
            $encrypted_password = $user['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $user;
            }
        } else {
            return NULL;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");

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

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // user existed 
            $stmt->close();
            return true;
        } else {
            // user not existed
            $stmt->close();
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>

注册数据存储在服务器上,但我在登录时收到此错误。好像我得到空的json对象。我正在使用000webhost。 我正在为一个重要的项目工作。请帮忙!!! 谢谢!

1 个答案:

答案 0 :(得分:1)

如下所示更改您的功能getUserByEmailAndPassword

将查询更改为以下内容或使其保持原样并更改$stmt->bind_result()  根据{{​​1}}查询检索到的列,$stmt->bind_result($col1, $col2, $col3)的方法。

SELECT *

也不要忘记对所有其他功能进行相对更改。

有关详细信息,请查看mysqli

的指南

希望它会帮助你。