8

我正在尝试将字符串数组作为 POST 数据传递给 PHP 脚本,但不确定该怎么做。

到目前为止,这是我执行 PHP 脚本的代码:

我试图传递数组的地方:

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);

调用 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();
}

和有问题的 PHP 脚本:

<?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);
?>

有任何想法吗?谢谢 !

编辑

我正在尝试以下但仍然没有快乐:

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);
}

这就是我所有的“错误报告”......

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

3 回答 3

20

要在查询字符串中将数组传递给 php,您应该添加[]到标识符并将每个项目添加为单独的条目,所以这样的事情应该可以工作:

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

现在,$_POST['devices']在 php 端将包含一个数组。

于 2013-04-06T13:51:08.833 回答
5

我认为您应该对您的设备数组进行 json 编码,以便获得一个可以将其传递给 BasicNameValuePair(...) 的字符串。在您的 php 代码中,您只需要使用 json_decode 来取回一个数组。

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

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

在您的 php 代码中:

$devices = $_POST['devices'];
$devices = json_decode($devices);
于 2013-04-06T13:41:59.583 回答
2

$_POST首先,在 PHP 中访问数组时缺少单引号。换行

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

到:

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

您应该使用 ini 值启用错误日志记录或 PHP 错误消息的输出以进行调试,display_errors以便注意到此类错误。log_errorserror_reporting


但甚至array($_POST['devices'])不会做预期的事情。array(...)是 php 中的数组初始化构造。这意味着您只需将 ($_POST['devices']) 包装到另一个数组中。

...想看看var_dump($_POST);. 这将使我有机会进一步提供帮助..

于 2013-04-06T13:35:03.543 回答