简体   繁体   English

从Android应用发送的POST数据未被PHP文件接收

[英]POST data sent from android app not being received by PHP file

I am trying to send data (a student id#) from an Android app to a PHP file via the body of an HTTP POST request. 我正在尝试通过HTTP POST请求的正文将数据(学生ID#)从Android应用程序发送到PHP文件。 Then the PHP file will send data (just a string for now) back to the app. 然后,PHP文件将数据(现在只是一个字符串)发送回应用程序。 However, my php doesn't seem to be able to read my POST data (student id#) from the request. 但是,我的PHP似乎无法从请求中读取我的POST数据(学生ID#)。

My .java file: 我的.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();

MY .PHP FILE: 我的.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);

My Android app is receiving a 200 response code and is receiving "test1" in the response, but not "test2", so the problem must be occuring when my PHP file tries to read the POST data: $id_in = trim($_POST['id_in']); 我的Android应用程序收到200响应代码,并且响应中收到“ test1”,但没有收到“ test2”,因此,当我的PHP文件尝试读取POST数据时,肯定是发生了问题: $id_in = trim($_POST['id_in']);

不要忘记使用urlConnection.connect();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM