android okhttp php post的发送和接收

时间:2025-01-26 12:55:15

android okhttp php post的发送和接收

关于登录验证涉及到的post提交验证
利用okhttp的post提交键值对的方法向php发送post,php接收后去获取Mysql的数据。


android 源码

OkHttpClient okHttpClient = new OkHttpClient();
//RequestBody formBody = new FormEncodingBuilder()获取键值对已经不再适用
                FormBody body = new ()
                        .add("name",name)
                        .add("id",id)
                        .build();
                Request request = new ()
                        .url("地址")
                        .post(body)
                        .build();
                try {
                    Response response = (request).execute();
                    String getInfo = ().string();
                } catch (IOException e) {
                    ();
                }

php源码

源码
<?php
//封装数据库的获取
$mysqli = new mysqli("localhost", "root", "", "info");
if(mysqli_connect_errno()){
    echo mysqli_connect_error();
}
$mysqli->set_charset("UTF8");
源码
<?php
header("Content-type:text/html;charset=utf-8");
include '';
$name =htmlspecialchars($_POST[name]);//$_POST[]获取客户端发送的post请求
$id =$_POST[id];
if($name==null && $id ==null) echo "未获取到信息";
    $sql = "select id,name,faculty from peopleinfo where id='$id'";
    $result = $mysqli->query($sql);
    $arr=array();//空的数组,该数组主要是格式化数据并封装成json格式发送到客户端
    if($row = $result->fetch_array()){
        $arr = array(
                'name'=>$row['name'],
                'id'=>$row['id'],
                'faculty'=>$row['faculty']
        );
        //封装json,如果php版本低于5.2,则不支持json_encode()方法,
        //可以参考本文件夹中php_json_encode.php中php_json_encode()方法代替json_encode();
        echo json_encode($arr);
    } else {
        $arr = array(
                'name'=>'',
                'id'=>'',
                'faculty'=>''
        ); //封装json,如果php版本低于5.2,则不支持json_encode()方法,
        //可以参考本文件夹中php_json_encode.php中php_json_encode()方法代替json_encode();
        echo json_encode($arr);
    }
    mysqli_free_result($result);
    mysqli_close($mysqli);

数据库info

表 peopleinfo
id name faculty
xxx xxx xxx