i have android application sends data via http post method php script , trying parse data store mysql. android app not written me have access source code have included below; sends data packed json array. php script right gets raw data , writes text file time being:
$filename = __dir__.directory_separator."jsontest.txt"; $postdata = file_get_contents("php://input"); file_put_contents($filename, "$postdata \n", file_append);
the text file writes out data this:
{"records":[{"name":"accelerator_pedal_position","value":15.400001,"timestamp":1367598908.278000},{"name":"engine_speed","value":1716.0,"timestamp":1367598908.285000},{"name":"vehicle_speed","value":32.040001,"timestamp":1367598908.290000},{"name":"brake_pedal_status","value":false,"timestamp":1367598908.293000},{"name":"fuel_consumed_since_restart","value":0.147325,"timestamp":1367598908.301000},{"name":"transmission_gear_position","value":"third","timestamp":1367598908.304000},{"name":"steering_wheel_angle","value":-2.3733,"timestamp":1367598908.307000},{"name":"fuel_consumed_since_restart","value":0.14745,"timestamp":1367598908.314000},{"name":"transmission_gear_position","value":"third","timestamp":1367598908.317000},{"name":"door_status","value":"driver","event":false,"timestamp":1367598908.320000},{"name":"door_status","value":"passenger","event":false,"timestamp":1367598908.326000},{"name":"door_status","value":"rear_left","event":false,"timestamp":1367598908.329000},{"name":"door_status","value":"rear_right","event":false,"timestamp":1367598908.331000},{"name":"odometer","value":0.0,"timestamp":1367598908.338000},{"name":"high_beam_status","value":false,"timestamp":1367598908.341000},{"name":"steering_wheel_angle","value":-2.3733,"timestamp":1367598908.343000},{"name":"engine_speed","value":1716.0,"timestamp":1367598908.351000},{"name":"powertrain_torque","value":74.0,"timestamp":1367598908.358000},{"name":"accelerator_pedal_position","value":12.1,"timestamp":1367598908.364000},{"name":"latitude","value":42.293911,"timestamp":1367598908.367000},{"name":"longitude","value":-83.238762,"timestamp":1367598908.376000},{"name":"engine_speed","value":1718.0,"timestamp":1367598908.380000},{"name":"vehicle_speed","value":32.200001,"timestamp":1367598908.382000},{"name":"brake_pedal_status","value":false,"timestamp":1367598908.391000},{"name":"transmission_gear_position","value":"third","timestamp":1367598908.393000}]}
this 1 of many "records" received. have mysql database set name, value, event, , timestamp columns , want each of these insert there received. have tried reading data using $_post , using json_decode no avail. below android code sending data:
public class uploadersink extends contextualvehicledatasink { private final static string tag = "uploadersink"; private final static int upload_batch_size = 25; private final static int maximum_queued_records = 5000; private final static int http_timeout = 5000; private uri muri; private blockingqueue<string> mrecordqueue = new linkedblockingqueue<string>(maximum_queued_records); private lock mqueuelock = new reentrantlock(); private condition mrecordsqueued = mqueuelock.newcondition(); private uploaderthread muploader = new uploaderthread(); /** * initialize , start new uploadersink immediately. * * @param uri uri send http post requests json data. */ public uploadersink(context context, uri uri) { super(context); muri = uri; } public uploadersink(context context, string path) throws datasinkexception { this(context, urifromstring(path)); } @override public void stop() { super.stop(); muploader.done(); } public boolean receive(rawmeasurement measurement) { string data = measurement.serialize(true); mrecordqueue.offer(data); if(mrecordqueue.size() >= upload_batch_size) { mqueuelock.lock(); mrecordsqueued.signal(); mqueuelock.unlock(); } return true; } /** * returns true if path not null , if valid uri. * * @param path uri validate * @return true if path valid uri. * */ public static boolean validatepath(string path) { if(path == null) { log.w(tag, "uploading path not set (it's " + path + ")"); return false; } try { urifromstring(path); return true; } catch(datasinkexception e) { return false; } } @override public string tostring() { return objects.tostringhelper(this) .add("uri", muri) .add("queuedrecords", mrecordqueue.size()) .tostring(); } private static uri urifromstring(string path) throws datasinkexception { try { return new uri(path); } catch(java.net.urisyntaxexception e) { throw new uploaderexception( "uploading path in wrong format -- expected: ip:port"); } } private static class uploaderexception extends datasinkexception { private static final long serialversionuid = 7436279598279767619l; public uploaderexception() { } public uploaderexception(string message) { super(message); } } private class uploaderthread extends thread { private boolean mrunning = true; public uploaderthread() { start(); } public void run() { while(mrunning) { try { arraylist<string> records = getrecords(); string data = constructrequestdata(records); httppost request = constructrequest(data); makerequest(request); } catch(uploaderexception e) { log.w(tag, "problem uploading record", e); } catch(interruptedexception e) { log.w(tag, "uploader interrupted", e); break; } } } public void done() { mrunning = false; } private string constructrequestdata(arraylist<string> records) throws uploaderexception { stringwriter buffer = new stringwriter(512); jsonfactory jsonfactory = new jsonfactory(); try { jsongenerator gen = jsonfactory.createjsongenerator(buffer); gen.writestartobject(); gen.writearrayfieldstart("records"); iterator<string> recorditerator = records.iterator(); while(recorditerator.hasnext()) { gen.writeraw(recorditerator.next()); if(recorditerator.hasnext()) { gen.writeraw(","); } } gen.writeendarray(); gen.writeendobject(); gen.close(); } catch(ioexception e) { log.w(tag, "unable encode data json -- " + "message may incomplete", e); throw new uploaderexception(); } return buffer.tostring(); } private httppost constructrequest(string data) throws uploaderexception { httppost request = new httppost(muri); try { bytearrayentity entity = new bytearrayentity( data.getbytes("utf8")); entity.setcontentencoding( new basicheader("content-type", "application/json")); request.setentity(entity); } catch(unsupportedencodingexception e) { log.w(tag, "couldn't encode records uploading", e); throw new uploaderexception(); } return request; } private void makerequest(httppost request) throws interruptedexception { httpparams parameters = new basichttpparams(); httpconnectionparams.setconnectiontimeout(parameters, http_timeout); httpconnectionparams.setsotimeout(parameters, http_timeout); final httpclient client = new defaulthttpclient(parameters); try { httpresponse response = client.execute(request); final int statuscode = response.getstatusline().getstatuscode(); if(statuscode != httpstatus.sc_created) { log.w(tag, "got unxpected status code: " + statuscode); } } catch(ioexception e) { log.w(tag, "problem uploading record", e); try { thread.sleep(5000); } catch(interruptedexception e2) { log.w(tag, "uploader interrupted after error", e2); throw e2; } } } private arraylist<string> getrecords() throws interruptedexception { mqueuelock.lock(); if(mrecordqueue.isempty()) { // queue thread safe, use lock // condition variable can use signal when batch has // been queued. mrecordsqueued.await(); } arraylist<string> records = new arraylist<string>(); mrecordqueue.drainto(records, upload_batch_size); mqueuelock.unlock(); return records; } }
}
your $postdata
variable first snippet contains json string. first want parse json_decode
.
$data = json_decode($postdata, true);
the true
second parameter makes associative array out of {}
objects in json structure, instead of php objects. use php objects if prefer, bit of modification below code (e.g. ->name
instead of ['name']
)
now, records in top-level key "records", , indexed array of objects want insert in database. can iterate through records this:
if (array_key_exists('records', $data) && is_array($data['records'])) { foreach ($data['records'] $record) { $name = $record['name']; // etc other properties, want them, e.g. echo "got name of '$name' value of '$value'"; // or insert database, or whatever } }
(update: added if
statement in above allow input not contain 'records' key or isn't array)
Comments
Post a Comment