1

I'm trying to get a php file to receive data from a JSONObject by POST request.

This is my android code in Kotlin:

    val jsonObject = JSONObject().apply {
        put("username", username)
        put("password", password)
        put("value", value)
        put("time", time)
    }
    val jsonObjectReq = JsonObjectRequest(Method.POST, url, jsonObject,
            Response.Listener { response ->
                Toast.makeText(this, response.getString("message"), Toast.LENGTH_LONG).show()
            },
            Response.ErrorListener {
                Toast.makeText(this, "Error", Toast.LENGTH_LONG).show()
            })
    Volley.newRequestQueue(this).add(jsonObjectReq)

I thought that in a php script, $_POST["username"] would get the username I put in the json object, but it doesn't. In fact the php script gets no post variables with my from the JsonObjectRequest. How do I get the values I put in the JSONObject in my php script and if I can't then what is the purpose of putting jsonObject in the constructor call for JSONObjectRequest?

K.R.
  • 446
  • 4
  • 12
  • 1
    The request coming into PHP won't have `$_POST` populated because JSON data is sent as raw data in the request body. Esstienally you need to read it from input. The code snippet from the duplicate `$json = file_get_contents('php://input'); $obj = json_decode($json);` is very likely what you need. Good luck :-). – HPierce Jan 10 '18 at 23:56
  • @HPierce, thanks that's basically what I needed. I just needed to change `$obj = json_decode($json);` to `$obj = json_decode($json, true)` so I could get it as an associative array. – K.R. Jan 11 '18 at 00:21

0 Answers0