JSON 从 Android 发送到计算引擎服务器 returns 空

JSON sent from Android to compute engine server returns null

我正在从我的 Android 应用向我的服务器发送 JSON 对象。在我的开发本地机器上它工作正常。我得到数据并对其进行解码。但是当我将服务器部署到计算引擎时,我没有在服务器端收到数据。数据从 Android 客户端发送。我还从我的浏览器中测试了 JSON,我得到了 200 响应代码。以下是代码片段:

//客户端

//在这里创建JSON对象 这是我发送的 JSON {"test", "1234"}

JSONObject json = new JSONObject();
json.put("test", args[0]);

String postData=json.toString();

// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.e("NOTIFICATION", "Sent");
os.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
    msg += line; 
}
Log.i("msg=",""+msg);

//服务器

<?php

   $json = file_get_contents("php://input");
   var_dump($json); //this returns String(0)
   $decoded = json_decode($json, TRUE);
   $pasid = $decoded['test'];

   echo"test if it works";
   var_dump($pasid); //returns null

无论我做什么,Android 应用程序都会发送一个字符串,但在服务器端我得到的是空字符串。到现在我都不知道为什么。

向服务器发送 post 请求后,您可以使用这些代码获得 post 正文:

<?php

  $post_body = file_get_contents("php://input");
  $json = json_decode($post_body);
  $pasid = $json->{"test"};

  echo $pasid;
?>

你的代码很混乱 这不是将数据从应用程序发送到远程数据库的好方法 你可以这样做`

形成应用程序

String uri="But your http URL";
URL url = new URL(uri);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
            con.setDoOutput(true);
            OutputStreamWriter writer=new     OutputStreamWriter(con.getOutputStream());
StringBuilder sb=new StringBuilder();
sb.append("username="+"Naham");
sb.append("password="+"passNaham");
            writer.write(sb.toString());
            writer.flush();

了解简单的 php 网络服务


    $data = array("result" => 0, "message" => "Error!");
    if ($_SERVER['REQUEST_METHOD'] == "POST") {
                $user_name = isset($_POST['username']) ? $_POST['user_name'] : "";
                $user_password = isset($_POST['user_password']) ?     $_POST['user_password'] : "";

               // do some thing here
    $data = array("result" => 1, "message" => "welcome");
    } else
        $data = array("result" => 0, "message" => "Error!");
    /* Output header */
    header('Content-type: application/json');
    echo json_encode($data);
    ?>


原来问题是由 HttpRLConnection 引起的。就像 the accepted answer in this SO question, 只是删除 `

urlConnection.setChunkedStreamingMode(0);

在哪里 `urlConnection = HttpUrlCooenction();

`