如何从Android OKHttp获取PHP中的JSON对象
我这里有我的OkHttp代码我在安卓系统工作如何从Android OKHttp获取PHP中的JSON对象,php,android,json,Php,Android,Json,我这里有我的OkHttp代码我在安卓系统工作 void postRequest(String postUrl, String postBody) throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON,postBody); Request request = new Request.Bu
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());
}
});
}
这是我的PHP部分
<?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'];
?>
我想获取通过JSON传递的值,但当我使用$\u POST时,它们以没有值结束。我尝试了的API,它确实发送了信息
感谢您的帮助。尝试以下方法:
//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;
当然,一切都取决于您如何武装发送的帖子主体,另一方面,如果您正在从android向php发出post请求,您不需要将变量转换为json,只需传递主体就可以了
您必须仅将php对android的答案转换为JSON
示例:根据您和我的评论,您可以执行以下操作:
<?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"];
进一步阅读:try$fgc=file\u get\u contentsphp://input; 然后是var_dump$fgc;看看你得到了什么。string224{nombre:A,apellidoPaterno:A,apellidoMaterno:A,direccion:A,redassocials:A,telefono:4,nombreUsuario:A,confirmar:}我不知道你在做什么,也不知道你是如何发送链的,但对于你在你发送的字符串中放置的样本,它应该是有效的。样本:
$json = json_decode($fgc);
// now you've got all your values as an object in $json:
$nombre = $json->nombre;