2014-06-20 48 views
1

我創建一個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/

質詢

  1. 有人能解釋什麼,我做錯了,一個合理的解決方案?
  2. php://輸入和$ _POST有什麼區別?

感謝

QUEST

+0

你不能這樣做'json_decode($ _ POST)'作爲$ _POST是一個數組。 –

+0

@DenisV謝謝,我是PHP的新手,那麼我如何解碼JSON對象? –

+0

您發送「發佈」請求,您可以在發佈請求中獲取數據。 PHP代碼像$ _POST ... – Rajnish

回答

3

使用此方法,使POST請求:

public String makePOSTRequest(String url, List<NameValuePair> nameValuePairs) { 
    String response = ""; 

    try { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     response = EntityUtils.toString(httpEntity); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    Log.d(LOGTAG, "POST Response >>> " + response); 
    return response; 

} 

用法:

在Java:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("json",jsonObject.toString())); 

String response = makePOSTRequest(String url, nameValuePairs); 

服務器端PHP:

$jsonInput = $_POST['json']; 
json_decode($jsonInput); 
+0

謝謝,作品像魅力! :) 你能解釋一下是怎麼回事,我做錯了什麼? –

0

當您發送POST請求到服務器,將在 '郵報' 得到的參數(按你的Android代碼)。

這裏是溶液:

if($_POST) 
{ 
    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()); 
}  
} 
else 
{ 
    echo "Please send data in HTTP POST REQUEST!"; 
} 

希望上述代碼應是有用的。