【问题标题】:POST data sent from android app not being received by PHP filePHP文件未接收到从Android应用程序发送的POST数据
【发布时间】:2016-04-16 20:59:19
【问题描述】:

我正在尝试通过 HTTP POST 请求的正文将数据(学生 ID#)从 Android 应用程序发送到 PHP 文件。然后 PHP 文件会将数据(现在只是一个字符串)发送回应用程序。但是,我的 php 似乎无法从请求中读取我的 POST 数据(学生 ID#)。

我的 .java 文件:

        JSONObject jsonParam = new JSONObject();
        DataOutputStream printout;
        String idIN = params[0];
        jsonParam.put("id_in", idIN);
        BufferedReader input;
        String result;


        URL url = null;
        HttpURLConnection urlConnection = null;

        url = new URL("http://10.0.2.2/project/connector.php");
        urlConnection = (HttpURLConnection) url.openConnection();

        //prepare request
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);  
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        printout = new DataOutputStream(urlConnection.getOutputStream ());

        //printout.write(jsonParam);
        printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));

        //this returns: {"id_in":"1010101"}
        Log.d("json out: ", jsonParam.toString());

        printout.flush();
        printout.close();

        int response = -1;

        response = urlConnection.getResponseCode();

        input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        result = input.readLine();

        // This returns 200
        Log.d("response code: ", result);

        urlConnection.disconnect();

我的 .PHP 文件:

 <?php

 header('Content-Type: text/html; charset=utf-8'); 

 $id_in = "";

 echo "test1";

 $id_in = trim($_POST['id_in']);

 echo "test2";

 if (isset($_POST['id_in'])) {
     echo "good";
 }else{
     echo "bad";
 }

 mysqli_close($myconn);

我的 Android 应用收到 200 响应代码并且在响应中收到“test1”,但不是“test2”,所以当我的 PHP 文件尝试读取 POST 数据时一定会出现问题:$id_in = trim($_POST['id_in']);

【问题讨论】:

  • JSON不能使用POST(),需要使用file_get_contents('php://input')

标签: java php android post


【解决方案1】:

别忘了使用 urlConnection.connect();

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 2012-12-09
    • 2015-04-11
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多