我设法构建了一个 JSON 数组,并且我有一个 onClick 事件,我通过 POST 将此 JSONArray 发送到将处理该数组的 php 文件。
现在我不知道数组是否到达目的地,PHP 是否正确解释了数组。我的 POST 调用(Android)的代码是:
Button bsave = (Button) findViewById(R.id.button3);
View.OnClickListener eventHandlerx = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
JSONObject j1;
JSONArray jsonarray=new JSONArray();
ListView lst = (ListView) findViewById(R.id.mylistview);
int count = lst.getCount();
for (int i = 0; i < count; i++)
{
ViewGroup row = (ViewGroup) lst.getChildAt(i);
TextView tvId = (TextView) row.findViewById(R.id.fID);
TextView tvNume = (TextView) row.findViewById(R.id.fTitlu);
TextView tvUM = (TextView) row.findViewById(R.id.fUM);
TextView tvPU = (TextView) row.findViewById(R.id.fPU);
TextView tvCant = (TextView) row.findViewById(R.id.fCant);
jsonarray.put("Item");
j1 = new JSONObject();
try {
j1.put("idx", newid);
j1.put("id", tvId.getText());
j1.put("nume", tvNume.getText());
j1.put("um", tvUM.getText());
j1.put("pu", tvPU.getText());
j1.put("cant", tvCant.getText());
} catch (JSONException e) {
e.printStackTrace();
}
jsonarray.put(j1);
}
Log.d("JSON array","Array to send:"+jsonarray.toString());
sendJson( urlx, jsonarray);
}
private void sendJson(final String urlx, final JSONArray jsonarray) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(urlx);
StringEntity se = new StringEntity( jsonarray.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
HttpEntity entity = response.getEntity();
if (entity != null) {
Log.e("POST response",EntityUtils.toString(entity));
}else{
Log.e("POST response","NULL "+EntityUtils.toString(entity));
}
}else{
Log.e("POST response","NULL");
}
} catch(Exception e) {
e.printStackTrace();
Log.e("postJSON","Error at POST with json:"+e.toString());
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
};
bsave.setOnClickListener(eventHandlerx);
如何检查数组是否已成功发布到 php?我假设我可以在一个 php 文件中做到这一点......但是我如何看到结果?无论我做什么,日志都会向我显示:
org.apache.http.conn.EofSensorInputStream@somehexa
所以我被困住了。请给我一些解决方案。php 文件应该是什么样子才能返回 POSTED 值,我的 Android 代码应该是什么样子才能解释结果(只需将其显示在 Log 之类的地方以进行调试)
我使用的php是:
<?php
ob_start();
var_dump($_POST);
die();
$json = file_get_contents('php://input');
$obj = json_decode($json);
print $obj;
result = $obj;
$page = ob_get_contents();
ob_end_flush();
$fp = fopen("output.txt","w");
fwrite($fp,$page);
fclose($fp);
?>
但是,该文件没有显示出来......而且 Eclipse 在日志中没有给我任何东西......
谢谢