2013-04-06 10 views
7

Sto provando a passare un array di stringhe a uno script PHP come dati POST ma non sono sicuro di cosa fare.Passaggio di array di stringhe a PHP come POST

Ecco il mio codice per l'esecuzione di script PHP finora:

Dove sto cercando di passare la matrice:

nameValuePairs.add(new BasicNameValuePair("message",message)); 
String [] devices = {device1,device2,device3}; 
nameValuePairs.add(new BasicNameValuePair("devices", devices));// <-- Can't pass String[] to BasicNameValuePair 
callPHPScript("notify_devices", nameValuePairs); 

chiamata script PHP:

public String callPHPScript(String scriptName, List<NameValuePair> parameters) { 
    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost("http://localhost/" + scriptName); 
    String line = ""; 
    StringBuilder stringBuilder = new StringBuilder(); 
    try { 
     post.setEntity(new UrlEncodedFormEntity(parameters)); 

     HttpResponse response = client.execute(post); 
     if (response.getStatusLine().getStatusCode() != 200) 
     { 
      System.out.println("DB: Error executing script !"); 
     } 
     else { 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent())); 
      line = ""; 
      while ((line = rd.readLine()) != null) { 
       stringBuilder.append(line); 
      } 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    System.out.println("DB: Result: " + stringBuilder.toString()); 
    return stringBuilder.toString(); 
} 

e lo script PHP in questione:

<?php 
include('tools.php'); 
// Replace with real BROWSER API key from Google APIs 
$apiKey = "123456"; 

// Replace with real client registration IDs 
$registrationIDs = array($_POST[devices]); <-- Where I want to pass array to script 

// Message to be sent 
$message = $_POST['message']; 

// Set POST variables 
$url = 'https://android.googleapis.com/gcm/send'; 

$fields = array(
       'registration_ids' => $registrationIDs, 
       'data'    => array("message" => $message), 
       ); 

$headers = array( 
        'Authorization: key=' . $apiKey, 
        'Content-Type: application/json' 
       ); 

// Open connection 
$ch = curl_init(); 

// Set the url, number of POST vars, POST data 
curl_setopt($ch, CURLOPT_URL, $url); 

curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); 

// Execute post 
$result = curl_exec($ch); 

// Close connection 
curl_close($ch); 

print_as_json($result); 
?> 

Qualche idea? Grazie !

Modifica

Sto cercando il seguente, ma ancora nessuna gioia:

public void notifyDevices(Message message) { 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    List<String> deviceIDsList = new ArrayList<String>(); 
    String [] deviceIDArray; 

    //Get devices to notify 
    List<JSONDeviceProfile> deviceList = getDevicesToNotify(); 

    for(JSONDeviceProfile device : deviceList) { 
     deviceIDsList.add(device.getDeviceId()); 
    } 

    //Array of device IDs 
    deviceIDArray = deviceIDsList.toArray(new String[deviceIDsList.size()]); 
    for(String deviceID : deviceIDArray) { 

     nameValuePairs.add(new BasicNameValuePair("devices[]", deviceID)); 

    } 

    //Call script 
    callPHPScript("GCM.php", nameValuePairs); 
} 

Questa è "la segnalazione degli errori" tutto il Ho ...

 HttpResponse response = client.execute(post); 
     if (response.getStatusLine().getStatusCode() != 200) 
     { 
      System.out.println("DB: Error executing script !"); 
     } 
+1

E riguardo 'nameValuePairs.add (nuovo BasicNameValuePair (" devices [] ", device1));', 'nameValuePairs.add (nuovo BasicNameValuePair (" devices [] ", device2));' ...? –

+0

@ dev-null-dweller: dovresti postarlo come risposta. –

+0

Ti darò una prova ora, grazie! – TomSelleck

risposta

19

passare una matrice a PHP in stringa di query, si dovrebbe aggiungere [] di identificatore e aggiungere ogni elemento come voce separata, in modo da qualcosa come questo dovrebbe funzionare:

nameValuePairs.add(new BasicNameValuePair("devices[]", device1)); 
nameValuePairs.add(new BasicNameValuePair("devices[]", device2)); 
nameValuePairs.add(new BasicNameValuePair("devices[]", device3)); 

ora, $_POST['devices'] sul lato php conterrà un array.

+0

Ehi, sto provando questo, ma non funziona, non so come ottenere Java per stampare gli errori PHP, quindi sto solo ricevendo un messaggio "Errore nell'esecuzione dello script". Ho aggiornato il mio post con il codice che sto cercando .. – TomSelleck

+0

$ _POST ['devices'], non è più array corretto ($ _ POST ['devices']); ¿? – delive

2

In primo luogo, mancano virgolette singole quando si accede alla matrice $_POST in PHP. Modificare la riga

$registrationIDs = array($_POST[devices]); 

a:

$registrationIDs = array($_POST['devices']); 

Si dovrebbe abilitare la registrazione degli errori o l'uscita dei messaggi di errore di PHP per il debug utilizzando il valore ini display_errors, log_errors, error_reporting per farsi notare di tali errori.


Ma anche array($_POST['devices']) non farà ciò che si può prevedere. array(...) è un costrutto di inizializzazione dell'array in php. Significa che ti basta avvolgere ($ _POST ['devices']) in un altro array.

... Desidera vedere l'output di var_dump($_POST);. Questo mi darebbe la possibilità di aiutare ulteriormente ..

+0

Non è questo il problema, prima funziona anche, ma si getta ulteriore avviso –

+0

Oh non l'ho visto, grazie! Come posso attivare gli errori ?? – TomSelleck

+1

È possibile impostare queste impostazioni su valori appropriati usando il file 'php.ini' (globalmente) o per script usando la funzione' ini_set ($ key, $ value) '. Nota il mio aggiornamento sul costrutto 'array (...)' – hek2mgl

4

Penso che dovresti codificare JSON sul tuo array di dispositivi in ​​modo da ottenere una stringa che puoi passare a BasicNameValuePair (...). Nel codice php, devi solo usare json_decode per recuperare un array.

JSONArray devices = new JSONArray(); 
devices.put(device1); 
devices.put(device2); 
devices.put(device3); 

String json = devices.toString(); 
nameValuePairs.add(new BasicNameValuePair("devices", devices)); 

Nel codice PHP:

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

@Tom celic Hai risolto? Sto anche avendo lo stesso problema. –

+0

cosa è nameValuePairs –

Problemi correlati