无法访问来自php

时间:2016-04-12 21:12:13

标签: php android okhttp3

我发送带有json对象的post请求到服务器中的php,但php一直告诉$ _POST是空的。

这是okhttp代码

    public String postConection(JSONObject pJson, String pUrl) throws IOException {
    final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String dirArchivo = "http://10.0.2.2/SoulStoreProject/"+pUrl;

    OkHttpClient client = new OkHttpClient();

    RequestBody body = RequestBody.create(JSON, pJson.toString());
    Request request = new Request.Builder()
            .url(dirArchivo)
            .post(body)
            .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

这是php代码

$nick = $_POST['nick'];
$password = $_POST['password']; 

$query = "
    INSERT INTO 
        players(nick, password) 
        VALUES($nick,$password)
    ";


$DB->Execute($query);

1 个答案:

答案 0 :(得分:2)

您是以JSON格式发布的,因此您需要使用file_get_contents('php://input')获取帖子,然后对其进行解码,以便将其作为数组。

$_POST仅适用于使用enctype=”multipart/form-data”

编码的帖子
$post = json_decode(file_get_contents('php://input'),true);

$nick = $post['nick'];
$password = $post['password']; 

$query = "INSERT INTO players(nick, password) VALUES(?,?)";
$sth = $DB->prepare($query);
$sth->Execute(array($nick, $password));