从安卓设备发送JSON数据到PHP并写入文本文件

3

我正在尝试获取一个在安卓设备上动态创建的特定JSON文件,并使用HTTP POST请求将数据发送到一个PHP脚本中,以便存储到文本文件中以供以后使用。最终,我还需要将数据保存在MySQL数据库中,但我正在逐步进行工作。JSON文件格式的示例如下:

{"timestamp": 1351181576.64078, "name": "engine_speed", "value": 714.0}
{"timestamp": 1351181576.64578, "name": "vehicle_speed", "value": 0.0}
{"timestamp": 1351181576.6507802, "name": "brake_pedal_status", "value": true}

这个文件是在Android上逐行动态创建的,因此我不能一次性发送整个文件,但我想把每一行在创建时发送到PHP脚本。我编写了一个基本的Android应用程序,当按下一个按钮时,它会获取一个JSONObject,并使用HTTP Post将其发送到PHP脚本。现在我不关心将实际的JSON文件解析为要发送的对象,而只是使用两个测试JSONObjects。PHP脚本可以轻松获取第一个对象并将其存储到文本文件中,但另一个对象始终读取为空值,我无法弄清原因。我对PHP和Android编程相对较新,不确定我是否以正确的方式发送和接收数据。以下是相关Android应用程序代码的片段:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button button = (Button) findViewById(R.id.sendData);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Perform action on click
            Toast.makeText(MainActivity.this, "button was pressed",
                    Toast.LENGTH_SHORT).show();
            try {
                JSONObject json = new JSONObject(); 
                json.put("timestamp", 1351181576.64078); 
                json.put("name", "engine_speed");
                json.put("value", 714.0);
                postData(json);

                JSONObject json2 = new JSONObject(); 
                json.put("timestamp", 1351181576.7207818); 
                json.put("name", "steering_wheel_angle");
                json.put("value", 11.1633);
                postData(json2);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });     
}

public void postData(JSONObject json) throws JSONException {
    HttpClient httpclient = new DefaultHttpClient();

    try { 
        HttpPost httppost = new HttpPost(URL);

        List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);    
        nvp.add(new BasicNameValuePair("json", json.toString()));
        //httppost.setHeader("Content-type", "application/json");  
        httppost.setEntity(new UrlEncodedFormEntity(nvp));
        HttpResponse response = httpclient.execute(httppost); 

        if(response != null) {
            InputStream is = response.getEntity().getContent();
            //input stream is response that can be shown back on android
        }

    }catch (Exception e) {
        e.printStackTrace();
    } 
}

以下是用PHP代码从HTTP POST获取数据并将其写入文本文件的方法:
<?php
   $filename = __DIR__.DIRECTORY_SEPARATOR."jsontest.txt";
   $json = $_POST['json'];
   $data = json_decode($json, TRUE);

   if(is_null($json) == false){
      file_put_contents($filename, "$json \n", FILE_APPEND);
      foreach ($data as $name => $value) {
         file_put_contents($filename, "$name -> $value  \t", FILE_APPEND);
      }
      file_put_contents($filename, "\n", FILE_APPEND);
   }

   $myFile = "jsontest.txt";
   $fh = fopen($myFile, 'r');
   $theData = fread($fh,  filesize($myFile));
   fclose($fh);
   ?>

   <meta http-equiv="refresh" content="3" >
   <html>
      <!-- Displaying the data from text file, not really needed -->
      <p><?php echo $theData; ?></p>
   </html>

现在输出的文本文件看起来像这样,第一个对象保存得非常好,而第二个对象则显示为空:

{"value":714,"timestamp":1.35118157664078E9,"name":"engine_speed"} 
value -> 714    timestamp -> 1351181576.64      name -> engine_speed    
{}
1个回答

7

您的问题在于您的安卓应用程序:

            JSONObject json = new JSONObject(); 
            json.put("timestamp", 1351181576.64078); 
            json.put("name", "engine_speed");
            json.put("value", 714.0);
            postData(json);

            JSONObject json2 = new JSONObject(); 
            json.put("timestamp", 1351181576.7207818); 
            json.put("name", "steering_wheel_angle");
            json.put("value", 11.1633);
            postData(json2);

您没有向 json2 中输入任何数据,而是在修改 json。然后,您将完全未修改的 - 因此为空的 - json2 对象发送到 PHP,它忠实地将其打印出来为 {}

如果您修复 Android 应用程序以正确填写 json2,则应该可以正常工作:

            JSONObject json2 = new JSONObject(); 
            json2.put("timestamp", 1351181576.7207818); 
            json2.put("name", "steering_wheel_angle");
            json2.put("value", 11.1633);
            postData(json2);

哦,我的天啊,我感觉自己像个白痴...总是那些小事情让我困扰。谢谢你的帮助! - mbecker73

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接