我創建一個Android應用程序,以JSON發送到服務器端的PHP腳本,並將其存儲在數據庫中使用POST發送JSON服務器在Android應用
下面是從應用程序的相關代碼
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://輸入行,那麼JSON對象不會被傳輸,但值「0,0」被插入到數據庫中
我認爲必須有一個錯誤以下從這裏教程和代碼的應用程序code.I'm http://hmkcode.com/android-send-json-data-to-server/
質詢
- 有人能解釋什麼,我做錯了,一個合理的解決方案?
- php://輸入和$ _POST有什麼區別?
感謝
QUEST
你不能這樣做'json_decode($ _ POST)'作爲$ _POST是一個數組。 –
@DenisV謝謝,我是PHP的新手,那麼我如何解碼JSON對象? –
您發送「發佈」請求,您可以在發佈請求中獲取數據。 PHP代碼像$ _POST ... – Rajnish