简体   繁体   English

将String数组作为POST传递给PHP

[英]Passing String array to PHP as POST

I am trying to pass a string array to a PHP script as POST data but am unsure of what to do. 我试图将一个字符串数组作为POST数据传递给PHP脚本但不确定该怎么做。

Here is my code for executing PHP scripts so far: 这是我到目前为止执行PHP脚本的代码:

Where I am trying to pass the array: 我试图传递数组的地方:

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

Call PHP 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();
}

And the PHP script in question: 和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);
?>

Any ideas? 有任何想法吗? Thanks ! 谢谢 !

Edit 编辑

I am trying the following but still no joy: 我正在尝试以下但仍然没有快乐:

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

This is all the "Error reporting" I have... 这就是我所有的“错误报告”......

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

To pass an array to php in query string, you should add [] to identifier and add every item as separate entry, so something like this should work: 要在查询字符串中将数组传递给php,您应该将[]添加到标识符并将每个项目添加为单独的条目,因此这样的事情应该起作用:

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

now, $_POST['devices'] on php side will contain an array. 现在,PHP端的$_POST['devices']将包含一个数组。

I think you should json encode your devices array so you get a string which you can pass it to BasicNameValuePair(...). 我认为你应该对你的设备数组进行json编码,这样你就可以获得一个字符串,你可以将它传递给BasicNameValuePair(...)。 In your php code, you just've to use json_decode to get back an array. 在你的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));

In your php code: 在你的PHP代码中:

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

First, you are missing single quotes when accessing the $_POST array in PHP. 首先,在PHP中访问$_POST数组时,您缺少单引号。 Change the line 改变线

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

to: 至:

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

You should enable error logging or the output of PHP error messages for debugging using the ini value display_errors , log_errors , error_reporting to get noticed of such errors. 您应该使用ini值display_errorslog_errorserror_reporting启用错误日志记录或PHP错误消息的输出以进行调试,以了解此类错误。


But even array($_POST['devices']) will not do what are may expecting. 但即使是array($_POST['devices'])也不会做出可能的预期。 array(...) is an array initialization construct in php. array(...)是php中的数组初始化构造。 Meaning that you just wrap ($_POST['devices']) into another array. 这意味着你只需将($ _POST ['devices'])包装到另一个数组中。

... Would like to see the output of var_dump($_POST); ...想看var_dump($_POST);的输出var_dump($_POST); . This would give me a chance to help further.. 这会让我有机会进一步帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM