【发布时间】:2014-06-20 11:19:55
【问题描述】:
我正在创建一个 android 应用程序以将 JSON 发送到服务器端 php 脚本并将其存储在数据库中
这是应用程序中的相关代码
public String POST(){
String url = "http://192.168.150.1/t2.php";
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.put("str", "bang");
jsonObject.put("lat", 3.10);
jsonObject.put("lon", 3.10);
json = jsonObject.toString();
Toast.makeText(this, json, Toast.LENGTH_LONG).show();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = "success";
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
这是 php 脚本
<?php
$connection = mysql_connect("192.168.150.1","****","****");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
echo "connection success\n";
$db_select = mysql_select_db("ps1",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
echo "db selections success";
?>
<html>
<head>
<title> hl</title>
</head>
<body>
<p>hello</p>
<?php
$js = json_decode(file_get_contents('php://input'));
//$js = json_decode($_POST); ------------ ******
$atr ='';
$val = '';
foreach ($js as $a => $v)
{
$atr = $atr.','.$a;
$val = $val.','.$v;
}
$atr = ltrim($atr,',');
$val = ltrim($val,',');
echo "insert into js (".$atr.") values (" .$val . ");";
$result = mysql_query("insert into js (".$atr.") values (" .$val . ");", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
?>
</body>
</html>
<?php
mysql_close($connection);
?>
现在,如果尝试从应用程序中的对象发送 JSON,则不会发生任何事情
但如果我尝试
curl -H "Content-Type: application/json" -d '{"str":"\"hello\"","lat":"3.1","lon":"5.2"}' localhost/ t2.php
从命令行它可以工作。
如果我尝试取消注释 $js = json_decode($_POST);在 PHP 脚本中添加一行并注释掉 php://input 行,那么 JSON 对象不会被传输,而是将值 "", 0,0 插入到数据库中
我认为应用程序代码一定有错误。我正在关注这里的教程和代码http://hmkcode.com/android-send-json-data-to-server/
问题
- 谁能解释我做错了什么以及一个可行的解决方案?
- php://input 和 $_POST 有什么区别?
谢谢
任务
【问题讨论】:
-
你不能做
json_decode($_POST)因为 $_POST 是一个数组。 -
@DenisV 谢谢,我是 PHP 新手,如何解码 JSON 对象?
-
您正在发送“发布”请求,您可以在发布请求中获取数据。 PHP 代码如 $_POST...
-
@Rajnish 你能再具体一点吗?
-
@Gokul_uf 检查这个:stackoverflow.com/questions/8945879/…