【问题标题】:RESTful API with Volley Kotlin doens't work带有 Volley Kotlin 的 RESTful API 不起作用
【发布时间】:2020-08-01 12:46:07
【问题描述】:

我在网上看到了许多其他问题和答案,但我还没有找到解决问题的方法。 基本上,我已经创建了一个 API 页面。如果我使用 API 测试器(例如 apitester.com),它可以正常工作。 相反,当我从 Volley (Android-Kotlin) 发出 POST 请求时,它不起作用。 看起来参数是空的。 我无法理解这个问题。

PHP 代码:

include_once($_SERVER['DOCUMENT_ROOT'] . "/include/variables.php");
global $localhost_db, $username_db, $password_db, $database_api;
header("Content-Type:application/json");
if ($c = new mysqli($localhost_db, $username_db, $password_db, $database_api)) {
    $c->set_charset("utf8");
    //POST request -> insert a new data to database
    $data = json_decode(file_get_contents('php://input'), true);
    $condition = isset($data["logged"]) && ($data["logged"] == 0 || $data["logged"] == 1) && isset($data["username"]) && isset($data["language"]);
    if ($condition) {
        $year = date('Y');
        $month = date("m");
        $day = date("d");
        $sql = "SELECT `date` FROM statistics WHERE `username`='" . $data["username"] . "' AND YEAR(`date`)=" . $year . " AND MONTH(`date`)=" . $month . " AND DAY(`date`)=" . $day;
        if ($r = $c->query($sql)) {
            if ($r->num_rows == 0) {
                $sql = "INSERT INTO statistics(`id`, `date`, `logged`, `username`, `language`) VALUES(NULL,'" . date("Y-m-d H:i:s") . "', '" . $data["logged"] . "', '" . $data["username"] . "', '" . $data["language"] . "')";
                if ($r = $c->query($sql)) {
                    response(200, "OK", "Record inserted correctly");
                } else {
                    response(500, "Error", "Can't insert record on database");
                }
            } else {
                response(400, "Error", "Record has already inserted today");
            }
        } else {
            response(400, "Error", "Something was wrong in POST request (1)");
        }
    } else {
        response(400, "Error", "Something was wrong in POST request (2). Received data> logged: " . $data["logged"] . ", language: " . $data["language"] . ", username: " . $data["username"]);
    }
} else {
    echo "Failed to connect to the database.";
    response(500, "Error", "Can't connect to the database");
}

function response($response_code, $response_status, $response_description)
{
    $response['code'] = $response_code;
    $response['status'] = $response_status;
    $response['description'] = $response_description;

    $json_response = json_encode($response);
    echo $json_response;
}
?>

而不是 Android Kotlin 代码:

var params = JSONObject()
params.put("username", username)
    params.put("logged", logged)
    params.put("language", language)

    val que = Volley.newRequestQueue(this)
    val req = object : JsonObjectRequest(Request.Method.POST, url_statistics, params,
        Response.Listener {
            val jsonResult = it.toString()
            var jsonResultArray = arrayOf(jsonResult, "")
            println(jsonResult)
            val jsonObj = JSONObject(
                jsonResultArray[0].substring(
                    jsonResultArray[0].indexOf("{"),
                    jsonResultArray[0].lastIndexOf("}") + 1
                )
            )
            if (jsonObj.getString("code")
                    .toInt() == 200
            ) {//Successful}
            else {//Error}
        }, Response.ErrorListener {
            //Error
        }
    ){}
    que.add(req)

【问题讨论】:

    标签: php android api kotlin post


    【解决方案1】:

    这样做:

    $username =  $_POST['username']
    

    代替:

     $data = json_decode(file_get_contents('php://input'), true);
    

    【讨论】:

    • 这绝对不行,因为 Volley 发送一个 Json。
    • 我用retrofit代替volley,好用,效率更高。我还用 PHP 开发了服务器端,它绝对有效。我认为您的客户端代码是正确的。
    猜你喜欢
    • 2021-06-21
    • 2023-03-27
    • 2022-07-15
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多