2011-06-17 100 views
1

我想讓Android設備發送數據到PHP服務器。接收後,PHP服務器將其他數據發送給Android。第一部分可以通過使用JSON來完成。但是,我不知道如何讓PHP服務器向Android發送數據。對不起,我是PHP新手!如何讓PHP服務器向Android設備發送數據

回答

1

無論您的PHP腳本「打印」什麼數據都會返回到Android設備上的響應中。

你可以做這樣的事情在PHP中:

<?php 
// TODO: Handle incoming data 

// Send JSON data back to client 
header('Cache-Control: no-cache, must-revalidate'); 
header('Content-type: application/json'); 

// Compute data 
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9); 

// Encode/print data 
echo json_encode($data); 
?> 

你會想取代你的代碼來處理從客戶端(安卓)提交的數據的第一個評論。然後,您將響應標頭設置爲application/jsonecho以反向您的編碼數據。

從技術上講,你可以用echo/print取回任何你喜歡的東西,但是使用像JSON這樣的格式可以更容易地解碼客戶端的數據。

+0

謝謝。你是對的。 – Peter

+0

@Pater如果您不介意,請將此答案標記爲正確。 –

2

我目前正在開發的是真實通信應用與PHP服務器(雙向通信,服務器發送數據到應用程序和應用程序發送數據到服務器),在objective-c [iphone],但原則是相同的我猜。
我們使用REST服務和JSON。

在你的情況下,它應該像這樣工作:
移動1通過REST調用將數據發送到REST服務器(它調用方法1服務器開發,例如,使用Zend_REST。),它將數據存儲在數據庫(以mySQL爲例)。
移動2週期性地向REST服務器發送請求到一個檢查mySQL中新條目的方法。如果有新的東西,它會用數據發送響應,否則發送錯誤。

1

這裏是一個Android的片段發送POST請求,一些虛假網站,發送電子郵件,密碼和數據串(你會把你的JSON數據串

HttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost("http://website.com/yourPageHere.php"); 
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("email", emailString)); 
nameValuePairs.add(new BasicNameValuePair("password", passwordString)); 
nameValuePairs.add(new BasicNameValuePair("data", yourDataString)); 

try { 
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
} catch (UnsupportedEncodingException e) { 
    //do stuff 
} 

HttpResponse response = null; 
try { 
    response = httpClient.execute(httpPost); 
} catch (ClientProtocolException e) { 
    //do stuff 
} catch (IOException e) { 
    //do stuff 
} 

if(response == null){ 
    //time out or other problem, fail gracefully 

} 

HttpEntity responseEntity = response.getEntity(); 

try { 
    String jsonString = EntityUtils.toString(responseEntity); 
    //jsonString is the full body of the response from the server 
    //if your php script is sending json, thats whats in here 
} catch (ParseException e) { 
    //do stuff 
} catch (IOException e) { 
    //do stuff 
} 

你的PHP腳本,yourPageHere .PHP 對待這就像任何其他的PHP腳本,你可能會寫,但不是返回HTML你是剛剛返回表示文本的JSON數據塊。

<?php 

header('Content-type: application/json'); 

/* 
here you can use the $_POST['email'], $_POST['password'] 
and $_POST['data'] indexes to access the data sent to 
you from the phone, then create a json string to return 
to the phone 
*/ 

/* you can convert php objects/arrays to json using 
json_encode($object), handle this however you 
want just so that $jsonString is the final 
representation of the json object */ 
$jsonString = 'blabla'; 


/* 
prints the string in the body of the response, 
this is the "jsonString" object found in the 
above android snippet. 
*/ 
echo $jsonString; // 
?> 

你可以做次上面用GET請求代替POST也是如此。 如果你是真的新的PHP你可能想要做一對夫婦形式的頁面樣本,以獲得閱讀url參數的掛起。

+0

謝謝。這正是我需要的。 – Peter

相關問題