从机器人发送的JSON数据,PHP和写入文本文件 [英] Sending JSON data from Android to PHP and writing to text file

查看:167
本文介绍了从机器人发送的JSON数据,PHP和写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想利用这是一个Android设备上动态创建一个特定的JSON文件,并使用HTTP POST请求的PHP脚本存储到供以后使用一个文本文件中发送数据。我最终还需要它,以便将数据保存在MySQL数据库中,但我的工作一步一个脚印的时间。什么样的JSON文件的格式看起来一个例子是这样的:

  {时间戳:1351181576.64078,名:engine_speed,价值:714.0}
{时间戳:1351181576.64578,名:vehicle_speed,价值:0.0}
{时间戳:1351181576.6507802,名:brake_pedal_status,价值:真}
 

此文件是动态创建通过对Android一行行,所以我不能同时发送整个文件,但每行,因为它是在我要发送到PHP脚本。我写了一个基本的Andr​​oid应用程序,当按钮是pssed $ P $,需要的JSONObject并把它发送到使用HTTP发布的PHP脚本。现在我担心的不是解析的实际JSON文件为对象进行发送,而只是用两个测试JSONObjects。 PHP脚本获得的第一个对象,并将其存储到文本文件中没有问题,但其他物体的不断读书为空,我想不通这是为什么。我是比较新的PHP和Android编程和我不知道如果我发送和接收的正确的方式的数据。以下是我的相关的Andr​​oid应用程序code段:

 保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    最后Button按钮=(按钮)findViewById(R.id.sendData);
    button.setOnClickListener(新View.OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            //执行上的点击动作
            Toast.makeText(MainActivity.this按钮是pssed $ P $,
                    Toast.LENGTH_SHORT).show();
            尝试 {
                JSONObject的JSON =新的JSONObject();
                json.put(时间戳,1351181576.64078);
                json.put(姓名,engine_speed);
                json.put(价值,714.0);
                POSTDATA(JSON);

                JSONObject的json2 =新的JSONObject();
                json.put(时间戳,1351181576.7207818);
                json.put(姓名,steering_wheel_angle);
                json.put(价值,11.1633);
                POSTDATA(json2);
            }赶上(JSONException E){
                e.printStackTrace();
            }

        }
    });
}

公共无效POSTDATA(JSONObject的JSON)抛出JSONException {
    HttpClient的HttpClient的=新DefaultHttpClient();

    尝试 {
        HttpPost httppost =新HttpPost(URL);

        名单<的NameValuePair> NVP =新的ArrayList<的NameValuePair>(2);
        nvp.add(新BasicNameValuePair(JSON,json.toString()));
        //httppost.setHeader("Content-type,应用/ JSON);
        httppost.setEntity(新UrlEn codedFormEntity(NVP));
        HTT presponse响应= httpclient.execute(httppost);

        如果(响应!= NULL){
            InputStream的是= response.getEntity()的getContent()。
            //输入流是响应可以显示,回到安卓
        }

    }赶上(例外五){
        e.printStackTrace();
    }
}
 

下面是PHP code从HTTP后取数据,并记录到一个文本文件中:

 < PHP
   $文件名= __DIR __ DIRECTORY_SEPARATORjsontest.txt。
   $ JSON = $ _ POST ['JSON'];
   $数据= json_de code($ JSON,TRUE);

   如果(is_null($ JSON)== FALSE){
      file_put_contents($文件名,$ JSON \ N,FILE_APPEND);
      的foreach($数据,$名称=> $值){
         file_put_contents($文件名,$名字 - > $值\ t的,FILE_APPEND);
      }
      file_put_contents($文件名,\ N,FILE_APPEND);
   }

   $ MYFILE =jsontest.txt;
   $ FH =的fopen($ MYFILE,'R');
   $海图= FREAD($跳频,档案大小($ MYFILE));
   fclose函数($ FH);
   ?>

   < META HTTP-当量=刷新内容=3>
   < HTML>
      <! - 从文本文件中显示的数据,而不是真正需要的 - >
      < P>< PHP的echo $海图; ?>&所述; / P>
   < / HTML>
 

现在输出的文本文件看起来像这样,第一个对象被保存完美的罚款,并显示为空的第二个对象:

  {值:714,时间戳:1.35118157664078E9,名:engine_speed}
价值 - > 714时间戳 - > 1351181576.64名字 - > engine_speed
{}
 

解决方案

您的问题是在你的Andr​​oid应用程序:

 的JSONObject JSON =新的JSONObject();
            json.put(时间戳,1351181576.64078);
            json.put(姓名,engine_speed);
            json.put(价值,714.0);
            POSTDATA(JSON);

            JSONObject的json2 =新的JSONObject();
            json.put(时间戳,1351181576.7207818);
            json.put(姓名,steering_wheel_angle);
            json.put(价值,11.1633);
            POSTDATA(json2);
 

您不会把任何数据到 json2 ,而是正在修改 JSON 。然后,您发送的完全未经修饰的 - 因此空 - json2 对象到PHP,这failthfully打印出来作为 {}

如果你解决你的Andr​​oid应用程序填写 json2 正确,事情应该工作:

 的JSONObject json2 =新的JSONObject();
            json2.put(时间戳,1351181576.7207818);
            json2.put(姓名,steering_wheel_angle);
            json2.put(价值,11.1633);
            POSTDATA(json2);
 

I am trying to take a specific JSON file that is dynamically created on an Android device and send that data using HTTP post requests to a PHP script to store into a text file for later use. Eventually I also need to make it so that the data is saved in a MySQL database but I am working one step at a time. An example of what the format of the JSON file looks is this:

{"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}

This file is dynamically created line by line on the Android, so I cannot send the whole file at once, but each line as it is created I want to send to the PHP script. I have written a basic Android application that, when a button is pressed, takes a JSONObject and sends it to the PHP script using HTTP Post. Right now I am not worrying about parsing the actual JSON file into objects to be sent, and am just using two test JSONObjects. The PHP script gets the first object and stores it into the text file no problem, but the other object its keeps reading as null, which I cannot figure out why. I am relatively new to PHP and Android programming and am not sure if I am sending and receiving the data in the right manner. Below are the segments of my related Android application code :

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();
    } 
}

Below is the PHP code to take the data from the HTTP Post and write it into a text file:

<?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>

Right now the output text file looks like this, with the first object being saved perfectly fine and the second object showing up as null:

{"value":714,"timestamp":1.35118157664078E9,"name":"engine_speed"} 
value -> 714    timestamp -> 1351181576.64      name -> engine_speed    
{}

解决方案

Your problem is in your Android application:

            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);

You are not putting any data in to json2, and instead are modifying json. You then send the completely unmodified - and therefore empty - json2 object to PHP, which failthfully prints it out as {}.

If you fix your Android application to fill out json2 correctly, things should work:

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

这篇关于从机器人发送的JSON数据,PHP和写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆