Reputation: 15
I have my OkHttp code here (i'm working in Android)
void postRequest(String postUrl, String postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON,postBody);
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
And this is my PHP part
<?php
header("Content-type: application/json; charset=utf-8");
include("conexion.php");
$nombre = $_POST["nombre"];
$apellidoPaterno = $_POST['apellidoPaterno'];
$apellidoMaterno = $_POST['apellidoMaterno'];
$direccion = $_POST['direccion'];
$redesSociales = $_POST['redesSociales'];
$telefono = $_POST['telefono'];
$nombreUsuario = $_POST['nombreUsuario'];
$contrasena = $_POST['contrasenaUsuario'];
?>
I want to obtain the values that are passing through my JSON, but when I use $_POST they end with no values. I've tried with the API of reqres and it does send the information.
Any help is appreciated, thanks.
Upvotes: 0
Views: 689
Reputation: 6943
Following your and my comments you could do the following:
<?php
// header("Content-type: application/json; charset=utf-8"); // not really needed here for now
include("conexion.php");
$fgc = file_get_contents("php://input");
$json = json_decode($fgc, true);
// now you've got all your values in $json:
$nombre = $json["nombre"];
alternatively you could do:
$json = json_decode($fgc);
// now you've got all your values as an object in $json:
$nombre = $json->nombre;
further reading: http://php.net/manual/de/wrappers.php.php#wrappers.php.input
Upvotes: 1
Reputation: 268
try this:
//this only you use to issue a response in json format from your php to android
//header("Content-type: application/json; charset=utf-8");
include("conexion.php");
//The following lines serve to receive a json and transform them to the variables
$data = json_decode($_POST);
$nombre = $data->nombre;
$apellidoPaterno = $data->apellidoPaterno;
$apellidoMaterno = $data->apellidoMaterno;
$direccion = $data->direccion;
$redesSociales = $data->redesSociales;
$telefono = $data->telefono;
$nombreUsuario = $data->nombreUsuario;
$contrasena = $data->contrasenaUsuario;
Of course everything depends on how you are arming the body of the post sent, on the other hand if you are making a post request from android to your php, you do not need to convert the variables to json, just pass the body and already.
You must convert to JSON only the answers of your php towards android.
SAMPLE: https://ideone.com/x2ENdd
Upvotes: 0