使用 Volley 连接到 PHP 来获取 JSON 对象响应


using volley connecting to php to get jsonobject response

    public void volley(){
    String url = "http://percyteng.com/get_users_details.php";
    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");
                        String useremail = jsonResponse.getString("useremail"),
                                password = jsonResponse.getString("password");
                        alert(useremail,password);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<>();
            // the POST parameters:
            params.put("useremail", etUsername.getText().toString());
            params.put("password", etPassword.getText().toString());
            return params;
        }
    };
    Volley.newRequestQueue(this).add(postRequest);

这是我的安卓 java 登录类中的凌空连接代码。我使用警报进行测试,发现这条线实际上不起作用。
JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");网址应该是正确的,下面是我的php代码。

`$response = array();`
// include db connect class
require_once __DIR__ . '/db_connect.php';
try{
    // connecting to db
    $con = new DB_CONNECT();
    $db = $con->connect();
    echo $_POST["useremail"];
    // check for post data
    if (isset($_POST["useremail"]) && isset($_POST["password"])) {
        $email = $_POST["useremail"];
        $password = $_POST["password"];
            // $useremail = "percytsy@gmail.com";
            // $password= "coolpig123";
            // echo "shit";
        // get a product from products table using PDO prepared statement
        $result = $db->prepare("SELECT * FROM user WHERE useremail = :useremail AND password = :password");
        echo "shit";
        $result->bindParam(":useremail", $useremail, PDO::PARAM_STR, 30);
        $result->bindParam(":password", $password, PDO::PARAM_STR, 25); 
        // bind the values individually
        //execute will execute db command with binded variables. Becaise we
        // binded first, the parameters for eceute() can be empty
        $result->execute();
        if (!empty($result)) {
            // check for empty result
            if ($result->rowCount() > 0) {
                $result = $result->fetch();
                $user = array();
                $user["useremail"] = $result["useremail"];
                $user["password"] = $result["password"];
                // success
                $response["success"] = 1;
                // user node
                $response["user"] = array();
                array_push($response["user"], $user);
                // echoing JSON response
                echo json_encode($response);
            } else {
                // no product found
                $response["success"] = 0;
                $response["message"] = "No user found";
                // echo no users JSON
                echo json_encode($response);
            }
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "Empty result";
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";
        // echoing JSON response
        echo json_encode($response);
    }
} catch(PDOException $e){
    print "Sorry, a database error occurred. Please try again later.'n";
    print $e->getMessage();
}
?>

我之前通过输入参数测试了 php 代码,它成功连接到我服务器上的 mysql。所以我想我的 php 代码应该没有问题。

另外,对问题的另一个猜测是我没有做一些基本的sudo apt-get....在我的服务器中进行Android和PHP连接,因为此问题事先发生。但是,我不知道我到底需要安装什么。

在传入请求之前,您需要通过调用以下代码来启动 Volley:

// Instantiate the cache
Cache cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
// Add request to queue
mRequestQueue.add(postRequest)